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?
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);
I've compared those two solutions:
Solution A:
// compatible Windows Phone 7.1, 8.0 and 8.1
public static string CalculateSHA1(string str)
{
var bytes = Encoding.UTF8.GetBytes(str);
byte[] sha1Bytes;
using (var algorithm = new SHA1Managed())
sha1Bytes = algorithm.ComputeHash(bytes);
return BitConverter.ToString(sha1Bytes).Replace("-", "").ToLowerInvariant();
}
Solution B (based on D for Developer):
// compatible Windows Phone 8.1 only
public static string CalculateSHA1New(string str)
{
var vector = CryptographicBuffer.ConvertStringToBinary(str, BinaryStringEncoding.Utf8);
var digest = HashAlgorithmProvider.OpenAlgorithm("SHA1").HashData(vector);
return CryptographicBuffer.EncodeToHexString(digest);
}
Well, solution A is like 40 times faster. So only use solution A. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With