Working with hmacsha256 in windows store app

让人想犯罪 __ 提交于 2019-12-10 03:14:49

问题


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


回答1:


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());
}



回答2:


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.



来源:https://stackoverflow.com/questions/13293420/working-with-hmacsha256-in-windows-store-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!