8

Windows Phone 7.1 アプリを Windows 8 ストア アプリに移行/変換/再構築しています。

WP7 アプリで使用している方法の 1 つが問題を引き起こしています。

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

4

2 に答える 2

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());
}
于 2014-02-18T22:06:25.640 に答える
1

new HMACSHA256(keydata) はキーを入力として使用しますが、MacAlgorithmProvider.CreateKey() は入力を「キーの生成に使用されるランダム データ」として使用しますが、これは HMAC アルゴリズムのキーではありません。

于 2012-11-08T16:58:49.187 に答える