我正在将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
答案 0 :(得分:7)
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());
}
答案 1 :(得分:1)
new HMACSHA256(keydata)使用密钥作为输入,而MacAlgorithmProvider.CreateKey()使用输入作为“用于帮助生成密钥的随机数据”,这不是HMAC算法的关键。