【问题标题】:Working with hmacsha256 in windows store app在 Windows 商店应用程序中使用 hmacsha256
【发布时间】:2012-10-28 21:47:30
【问题描述】:

我正在将 Windows Phone 7.1 应用程序迁移/转换/重建到 Windows 8 应用商店应用程序。

我在 de WP7 应用程序中使用的一种方法给我带来了麻烦:

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

查看 Windows 应用商店应用程序的文档,我想出了这个新代码,我希望它会给出相同的结果。但不是。我做错了什么。但是什么?

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

我不是密码学专家。我不确定我在做什么。也许有人可以帮助我。

谢谢, JP

【问题讨论】:

  • “我在 de WP7 应用程序中使用的一种方法给我带来了麻烦”为什么?缺少方法/类?例外?详细信息将帮助您。

标签: c# windows-phone-7 cryptography microsoft-metro


【解决方案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());
}

【讨论】:

  • 请添加一些上下文来解释为什么您的代码回答了 OP 的问题。
  • 谢谢你,几乎正是我想要的。
【解决方案2】:

new HMACSHA256(keydata) 使用密钥作为输入,而 MacAlgorithmProvider.CreateKey() 使用输入作为“用于帮助生成密钥的随机数据”,这不是 HMAC 算法的密钥。

【讨论】:

  • 抱歉 Nickolay,我不明白。正如我所说,我不是加密货币方面的专家。新的 HMACSHA256(keydata) 是什么意思?
  • 我的意思是 HMACSHA256 类的构造函数使用 keydata 作为密钥本身,而 MacAlgorithmProvider.CreateKey - 作为密钥生成器的输入。
  • 我不能再使用新的 HMACSHA256(secretKeyBytes)。 Windows 商店应用程序不支持它。所以我得想办法。
猜你喜欢
  • 1970-01-01
  • 2014-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多