我有旧代码,想在.NET Standard 2.0中使用它。我找到了System.Security.Cryptography.HMACSHA1,我知道如何计算哈希,但我不知道如何进行签名。如何使用.NET Standard 2编写下面的代码?
public string GenerateSignature(string key, string content)
{
var keyMaterial = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf8);
var macAlgorithm = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1");
var macKey = macAlgorithm.CreateKey(keyMaterial);
var buffer = CryptographicBuffer.ConvertStringToBinary(content, BinaryStringEncoding.Utf8);
var signatureBuffer = CryptographicEngine.Sign(macKey, buffer);
var signature = CryptographicBuffer.EncodeToBase64String(signatureBuffer);
return signature;
}
答案 0 :(得分:4)
许多HMAC内容在净标准和旧版本之间没有变化。以下代码应适用于.NET 4.5.1,Net Standard 1.3及更高版本以及.NET Core。它略微适应工作代码以匹配您的方法
public string GenerateSignature(string key, string content)
{
var hmac = new System.Security.Cryptography.HMACSHA1();
hmac.Key = Encoding.UTF8.GetBytes(key);
var contentBytes = Encoding.UTF8.GetBytes(content);
var signature = hmac.ComputeHash(contentBytes);
return Convert.ToBase64String(signature);
}