【问题标题】:Signing message in .NET Standard 2.0 with HMACSHA使用 HMACSHA 在 .NET Standard 2.0 中签名消息
【发布时间】:2017-09-29 12:32:12
【问题描述】:

我有旧代码,想在 .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;
        }

【问题讨论】:

    标签: c# .net-core-2.0 .net-standard-2.0


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-21
      • 2017-12-29
      • 2022-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多