Reputation: 34800
I want to hash/encode a unique integer (database ID) to create a similarly unique string.
It needs to meet the following requirements:
The result does not need to be reversible, just repeatable - so a 1-way hash would be fine.
Upvotes: 1
Views: 3236
Reputation: 100547
If you are fine with reversible (as Base36) than there is already built in Base16 (hex) formatting that probably would work too to slightly hide the number from regular people: String.Format("{0:x}", 1235)
or 12345.ToString("x")
Upvotes: 1
Reputation: 108810
A simple solution would be a base 36 encoding. The output will be a string between one and six characters.
public static string EncodeBase36(int i)
{
Contract.Requires<ArgumentException>(i>=0);
//Base conversion
string s="";
while(i!=0)
{
int digit = i % 36;
i/=36;
if(digit<10)
s=((char)('0'+digit)).ToString()+s;
else
s=((char)('a'+digit-10)).ToString()+s;
}
// Enforce minimum length
while(s.Length<3)
{
s = "0" + s;
}
return s;
}
Upvotes: 4
Reputation: 14386
Is there a reason why you cannot use base 64 encoded MD5 using the MD5CryptoServiceProvider
Class or SHA1 using the SHA1CryptoServiceProvider
Class? I am not aware of a cryptanalysis of base 36 but I would guess the collision rate is probably better with MD5 or SHA1.
Upvotes: 1