9

I am using the following code to perform SHA256.

public static string GenerateSaltedHash(string plainTextString, string saltString)        
        {            
            byte[] salt = Encoding.UTF8.GetBytes(saltString);
            byte[] plainText = Encoding.UTF8.GetBytes(plainTextString);
            HashAlgorithm algorithm = new SHA256Managed();

            byte[] plainTextWithSaltBytes =
              new byte[plainText.Length + salt.Length];

            for (int i = 0; i < plainText.Length; i++)
            {
                plainTextWithSaltBytes[i] = plainText[i];
            }
            for (int i = 0; i < salt.Length; i++)
            {
                plainTextWithSaltBytes[plainText.Length + i] = salt[i];
            }
            byte[] bytes = algorithm.ComputeHash(plainTextWithSaltBytes);
            return Convert.ToBase64String(algorithm.ComputeHash(plainTextWithSaltBytes));                              
        }

As I am using SHA256, I expect the length of the result to be 64. But I am getting 44.

What is the issue? Will the shorter length output impact security?

shim
  • 9,289
  • 12
  • 69
  • 108
Mangesh Kulkarni
  • 311
  • 1
  • 5
  • 13
  • 2
    As a guess - it looks like you're converting it into a Base64 string instead of the standard Hex string - which would give a different length. – Origin Jan 07 '15 at 10:34
  • 1
    SHA256 will give you 32 bytes as a hash. using Base64 encoding of this gives you approx 44 chars. as @origin said, if instead you represent each byte as its hex value (2 chars) then you'll get 64 chars. – Simon Halsey Jan 07 '15 at 10:42
  • Ya I think its right. I have converted each byte to string with X2 format & I am getting length of 64. – Mangesh Kulkarni Jan 07 '15 at 11:09

1 Answers1

18

Base-64 is 6 bits per character (2^6 = 64).

256 bits / 6 bits per char = 42.6666 char

And that has obviously ended up as 44 due to padding (you will see one or 2 = on the end of the output).

You must be expecting base-16 (AKA hexadecimal) which is 4 bits per character (2^4 = 16).

256 bits / 4 bits per char = 64 char

For hex use this:

return BitConverter.ToString(bytes).Replace("-", string.Empty);
Community
  • 1
  • 1
weston
  • 54,145
  • 21
  • 145
  • 203
  • Are there any differences in security by using this method or the Base64 method? – Dalton Apr 03 '18 at 10:42
  • 1
    No, they are both just encodings. Anyone with the base 64 or base 16 information can get back to the original binary representation easily. – weston Apr 03 '18 at 11:34