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

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...