簡體   English   中英

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

[英]I need to Hash a message with a key using Sha256 on 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");
        }

這是最終的工作代碼

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

您可以使用Windows.Security.Cryptography的類創建消息身份驗證代碼(問題中的鍵哈希)。 這是一個例子。 請按原樣提供它作為演示代碼。 對與安全性關聯的所有代碼進行全面的安全性檢查。

var clear = "foobarbaz";
var bytes = CryptographicBuffer.ConvertStringToBinary(clear, BinaryStringEncoding.Utf8);
var macProvider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256);
var rndKey = CryptographicBuffer.GenerateRandom(macProvider.MacLength);
var key = macProvider.CreateKey(rndKey);
var cypherMac = CryptographicEngine.Sign(key, bytes);
var asString = CryptographicBuffer.EncodeToBase64String(cypherMac);

根據.NET Framework文檔,您使用的類在.NET 4.5中可用,並且在Windows 8中受支持。
http://msdn.microsoft.com/zh-CN/library/system.security.cryptography.hmacsha256.aspx

如果您正在談論WinRT運行時,那么可能就是您想要的: http : //channel9.msdn.com/Forums/TechOff/Porting-to-WinRT/4df7586e1ef5400682eda00f0143b610

這對我有用:

using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;

string str = "your string";
string hash = CryptographicBuffer.EncodeToHexString(HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha256).HashData(CryptographicBuffer.ConvertStringToBinary(str, BinaryStringEncoding.Utf8)));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM