Take the 2-minute tour ×

Possible Duplicate:
Hash Function .NET


I should write an app that take string input and compute the hash value for the string (the maximun characters of the input is 16), the output should be in length of 22 characters (or less but not more) on base64 format.

I see that .NET framework suggests several hash functions, and I don't know what to use, does anyone have asuggest to me what is the best function to use, and how can I limit the output to 22 characters (on base64)?


share|improve this question
You posted exactly the same question twice! –  Marcelo Cantos Mar 7 '11 at 7:17
@Marcelo - To be fair he did specify "(on base64)". –  ChaosPandion Mar 7 '11 at 7:19
If you have an error in one of your questions, you could use the edit button just below your question to change your questions. –  Fun Mun Pieng Mar 7 '11 at 7:23
add comment

marked as duplicate by Ani, Marcelo Cantos, ChaosPandion, Guffa, Cody Gray Mar 7 '11 at 7:22


1 Answer

up vote 0 down vote accepted

You could use any of the hashing function and simply truncate the hash to the required size, then convert to base-64. In your case, you would need to truncate the hash to 15-bytes, which ends up as 20-bytes of base-64. I'm going to reuse my previous example.

string secretKey = "MySecretKey";
string salt = "123";
System.Security.Cryptography.SHA1 sha = System.Security.Cryptography.SHA1.Create();
byte[] preHash = System.Text.Encoding.UTF32.GetBytes(secretKey + salt);
byte[] hash = sha.ComputeHash(preHash);
string password = prefix + System.Convert.ToBase64String(hash, 0, 15);
share|improve this answer
yes, but I want to ensure that diffrents strings not give me same hase, trunncat the out put is a risk that I give collisions, and can you explain why I should defined "salt", why not uses only the "secretKey"? –  RRR Mar 7 '11 at 7:31
salt gives an added randomness to the hash output. It is not compulsory, but if your data needs to be secure, it is advised to have an extra salt. Truncating will not increase collision anymore than any other way. After all, your requirement is 22-byte length. You will eventually have to truncate one way or another. An alternative would be to do compression before hashing if you think the added complexity is not a problem but the risk of collision is. –  Fun Mun Pieng Mar 7 '11 at 7:45
@RRR, your 16-byte input if converted to base-64 results in 24 bytes. –  Fun Mun Pieng Mar 7 '11 at 8:03
add comment
