Search code examples
c#windows-phone-7.1sha1

Generating a SHA1 hash in Windows Phone outputs a different hash


I'm currently using the built-in methods in Windows Phone and Silverlight to create a SHA1 hash of a string. This is the code:

private static string CalculateSHA1(string text)
    {
        SHA1Managed s = new SHA1Managed();
        UTF8Encoding enc = new UTF8Encoding();
        s.ComputeHash(enc.GetBytes(text.ToCharArray()));
        System.Diagnostics.Debug.WriteLine("Original Text {0}, Access {1}", text, Convert.ToBase64String(s.Hash));
        return Convert.ToBase64String(s.Hash);
    }

For example, I tried generating a hash for this string: "hello".

Silverlight Output: LPJNul+wow4m6DsqxbninhsWHlwfp0JecwQzYpOLmCQ=

Correct Output: aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d

What I am doing wrong in the code?


Solution

  • In your example, you are Base64 encoding the byte array. Your correct output is in hexadecimal format, which you can achieve using:

    return BitConverter.ToString(s.Hash).Replace("-", "");
    

    instead of:

    return Convert.ToBase64String(s.Hash);