0

Possible Duplicate:
Hash Function .NET

hi,

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)?

thanks

3
  • You posted exactly the same question twice! Commented Mar 7, 2011 at 7:17
  • @Marcelo - To be fair he did specify "(on base64)". Commented Mar 7, 2011 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. Commented Mar 7, 2011 at 7:23

1 Answer 1

4

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); 
Sign up to request clarification or add additional context in comments.

3 Comments

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"?
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.
@RRR, your 16-byte input if converted to base-64 results in 24 bytes.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.