Working with hmacsha256 in windows store app

2020-08-26 10:43发布

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

2条回答
霸刀☆藐视天下
2楼-- · 2020-08-26 11:33

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.

查看更多
聊天终结者
3楼-- · 2020-08-26 11:46
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());
}
查看更多
登录 后发表回答