Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with hmacsha256 in windows store app

I'm migrating/converting/rebuilding a Windows Phone 7.1 app to a Windows 8 Store App.

One method I am using in de WP7 app is giving me trouble:

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 Windows Store Apps I came up with this new code which I hoped would give 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'm not an expert on Cryptography. I'm not sure what I'm doing. Maybe there is somebody out there who can help me.

Thanx, JP

like image 787
JP Sonnemans Avatar asked Nov 08 '12 16:11

JP Sonnemans


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());
}
like image 128
Srđan Božović Avatar answered Nov 02 '22 20:11

Srđan Božović


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

like image 34
Nickolay Olshevsky Avatar answered Nov 02 '22 21:11

Nickolay Olshevsky