加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:13:18 所属栏目:百科 来源:网络整理
导读:我需要在PCL(为Xamarin Forms开发)中生成HMAC-SHA256哈希,它不支持.NET内置的HMAC /加密类,所以我正在使用BouncyCastle来实现我的加密类. 我需要生成HMAC-SHA256哈希,但我无法在Google上找到任何示例,BouncyCastle似乎也没有任何相关文档.谁能帮我吗? 解决
我需要在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);
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读