Working with hmacsha256 in a Windows Store app

I am moving / converting / rebuilding a Windows Phone 7.1 application into a Windows 8 storage application.

One method that I use in a WP7 application gives me problems:

private byte[] GetSHA256Key(string data, string secretKey) { byte[] value = Encoding.UTF8.GetBytes(data); byte[] secretKeyBytes = Encoding.UTF8.GetBytes(secretKey); HMACSHA256 hmacsha256 = new HMACSHA256(secretKeyBytes); byte[] resultBytes = hmacsha256.ComputeHash(value); return resultBytes; } 

Looking at the documentation for the Windows Store apps, I came up with this new code, which I hoped would produce the same result. But no. I'm doing something wrong. But what?

 private byte[] GetSHA256Key(string value, string secretKey) { // Create a MacAlgorithmProvider object for the specified algorithm. MacAlgorithmProvider objMacProv = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256); // Create a buffer that contains the message to be signed. IBuffer valueBuffer = CryptographicBuffer.ConvertStringToBinary(value, BinaryStringEncoding.Utf8); // Create a key to be signed with the message. IBuffer buffKeyMaterial = CryptographicBuffer.ConvertStringToBinary(secretKey, BinaryStringEncoding.Utf8); CryptographicKey cryptographicKey = objMacProv.CreateKey(buffKeyMaterial); // Sign the key and message together. IBuffer bufferProtected = CryptographicEngine.Sign(cryptographicKey, valueBuffer); DataReader dataReader = DataReader.FromBuffer(bufferProtected); byte[] bytes = new byte[bufferProtected.Length]; dataReader.ReadBytes(bytes); return bytes; } 

I am not a specialist in cryptography. I'm not sure what I'm doing. Maybe there is someone who can help me.

Thanx, in JP

+8
c # cryptography windows-phone-7 microsoft-metro
source share
2 answers
 using System.Runtime.InteropServices.WindowsRuntime; private string GetSHA256Key(byte[] secretKey, string value) { var objMacProv = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256); var hash = objMacProv.CreateHash(secretKey.AsBuffer()); hash.Append(CryptographicBuffer.ConvertStringToBinary(value, BinaryStringEncoding.Utf8)); return CryptographicBuffer.EncodeToBase64String(hash.GetValueAndReset()); } 
+7
source share

new HMACSHA256 (keydata) uses the key as input, while MacAlgorithmProvider.CreateKey () uses the input as "Random data used to generate the key", which is not the key for the HMAC algorithm.

+1
source share

All Articles