我需要在PCL中生成一个HMAC- so 256散列(为Xamarin窗体开发),它不支持.NET内置的HMAC/加密类,因此我正在使用BouncyCastle来实现我的加密类。
我需要生成一个HMAC- for 256散列,但是我还没有在Google上找到任何例子,BouncyCastle似乎也没有这方面的任何文档。有人能帮我吗?
发布于 2016-04-27 02:47:20
多亏了解决方案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, 0, 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);
}
}发布于 2017-11-09 14:54:20
使用BouncyCastle https://www.nuget.org/packages/BouncyCastle-PCL/1.0.0.6的PCL分支非常简单,实际上与windows完全相同。
public string ComputeHMAC(string message)
{
var keyBytes = Encoding.UTF8.GetBytes(Constants.API_KEY);
var messageBytes = Encoding.UTF8.GetBytes(message);
var hmac = new HMACSHA256(keyBytes);
byte[] result = hmac.ComputeHash(messageBytes);
return Convert.ToBase64String(result);
}并使用实际的.Net版本进行单元测试:
[Test, AutoMoqData]
public void Hash_Algorithm_Correct (
[NoAutoProperties] HashMacService sut,
string message)
{
string expected;
var key = Encoding.UTF8.GetBytes(Constants.API_KEY);
using (var hmac = new HMACSHA256(key))
{
var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(message));
expected = Convert.ToBase64String(hash);
}
var result = sut.ComputeHMAC(message);
Assert.That(result, Is.EqualTo(expected));
}我使用的是PCLCrypto,但是它一直在Xamarin iOS上崩溃,它更干净,可以进行单元测试,而PCLCrypto需要平台apis,所以必须部署到设备上。
https://stackoverflow.com/questions/36876641
复制相似问题