3

I should write an app that takes string input and computes 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 many hash functions, and I have no idea what to use, can anyone please recommend me what is the best function to use, and how can I limit the output to 22 characters?

Thanks

3
  • 2
    Are you going to use the hash-function for cryptographic purposes or for a hash-table? Commented Mar 7, 2011 at 6:55
  • @Ani: 22-bytes of base64 output suggests a cryptographic hash function rather than a hash-table (which typically uses a machine word-sized hash). Commented Mar 7, 2011 at 7:33
  • 2
    MD5 [Link][1] and SHA-1 are not secure anymore. Go for SHA-2 or SHA-3 [1]: security.stackexchange.com/questions/19906/… Commented Oct 6, 2014 at 18:18

3 Answers 3

7

You can use MD5 which gives a 128 bit output and then throw away the last two characters when converted to base64, as they'll always be "==" (padding). This should give you 22 characters.

string GetEncodedHash(string password, string salt)
{
   MD5 md5 = new MD5CryptoServiceProvider();
   byte [] digest = md5.ComputeHash(Encoding.UTF8.GetBytes(password + salt);
   string base64digest = Convert.ToBase64String(digest, 0, digest.Length);
   return base64digest.Substring(0, base64digest.Length-2);
}
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

22 base64 characters means a 16-byte output from your hash function; you can use any hash function that outputs 128 bits.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.