使用BouncyCastle生成HMAC-SHA256哈希

Leo*_*ens 6 .net c# bouncycastle sha256 hmac

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

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

Leo*_*ens 6

感谢这里的解决方案,我想出了这段代码:

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, 0, bytes.Length);
        hmac.DoFinal(result, 0);

        return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

相应的单元测试(使用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);
    }
}
Run Code Online (Sandbox Code Playgroud)