我需要在Windows 8上使用Sha256使用密钥散列消息

She*_*wzy 1 c# sha256 windows-8

所以在过去,我曾经使用过Windows 8中没有的System.Security.Cryptography.我在Windows 8中找到的是windows.security,但我没有找到任何关于如何使用Sha256键的示例.这是我在System.Security.Cryptography中使用的旧代码

        string appID = "appid";
        string key = "password";
        var hmacsha256 = new HMACSHA256(Encoding.Default.GetBytes(key));
        hmacsha256.ComputeHash(Encoding.Default.GetBytes(appID));
        string k = "";
        foreach (byte test in hmacsha256.Hash)
        {
            k += test.ToString("X2");
        }
Run Code Online (Sandbox Code Playgroud)

She*_*wzy 6

所以这是最终的工作代码

public static string ComputeSignature (string algorithmName, string content, string key, BinaryStringEncoding encoding = BinaryStringEncoding.Utf8)
{   
    var algorithmProvider = MacAlgorithmProvider.OpenAlgorithm(algorithmName);
    var contentBuffer = CryptographicBuffer.ConvertStringToBinary(content, encoding);
    var keyBuffer = CryptographicBuffer.ConvertStringToBinary(key, encoding);
    var signatureKey = algorithmProvider.CreateKey(keyBuffer);
    var signedBuffer = CryptographicEngine.Sign(signatureKey, contentBuffer);
    return CryptographicBuffer.EncodeToHexString(signedBuffer);
}
Run Code Online (Sandbox Code Playgroud)