微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 使用BouncyCastle生成HMAC-SHA256哈希

我需要在PCL(为Xamarin Forms开发)中生成HMAC-SHA256哈希,它不支持.NET内置的HMAC /加密类,所以我正在使用BouncyCastle来实现我的加密类.

我需要生成HMAC-SHA256哈希,但我无法在Google上找到任何示例,BouncyCastle似乎也没有任何相关文档.谁能帮我吗?

解决方法

感谢 here解决方案,我提出了这个代码
public class HmacSha256
{
    public byte[] Hash(string text,string key)
    {
        var hmac = new HMac(new Sha256Digest());
        hmac.Init(new KeyParameter(Encoding.UTF8.GetBytes(key)));
        byte[] result = new byte[hmac.GetMacSize()];
        byte[] bytes = Encoding.UTF8.GetBytes(text);

        hmac.BlockUpdate(bytes,bytes.Length);
        hmac.DoFinal(result,0);

        return result;
    }
}

相应的单元测试(使用FluentAssertions):

[TestClass]
public class HmacSha256Tests
{
    private readonly HmacSha256 _hmac = new HmacSha256();

    [TestMethod]
    public void Hash_GeneratesValidHash_Forinput()
    {
        // Arrange
        string input = "hello";
        string key = "test";
        string expected = "F151EA24BDA91A18E89B8BB5793EF324B2A02133CCE15A28A719ACBD2E58A986";

        // Act
        byte[] output = _hmac.Hash(input,key);

        string outputHex = BitConverter.ToString(output).Replace("-","").toupper();

        // Assert
        expected.Should().Be(outputHex);
    }
}

原文地址:https://www.jb51.cc/csharp/238993.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐