C# PCL HMACSHAX with BouncyCastle-PCL
本文关键字:BouncyCastle-PCL with HMACSHAX PCL | 更新日期: 2023-09-27 17:57:24
我想在可移植的C#类中实现此逻辑:
static JsonWebToken()
{
HashAlgorithms = new Dictionary<JwtHashAlgorithm, Func<byte[], byte[], byte[]>>
{
{ JwtHashAlgorithm.HS256, (key, value) => { using (var sha = new HMACSHA256(key)) { return sha.ComputeHash(value); } } },
{ JwtHashAlgorithm.HS384, (key, value) => { using (var sha = new HMACSHA384(key)) { return sha.ComputeHash(value); } } },
{ JwtHashAlgorithm.HS512, (key, value) => { using (var sha = new HMACSHA512(key)) { return sha.ComputeHash(value); } } }
};
}
但是HMACSHA256
,HMACSHA384
和HMACSHA512
在便携式中不存在图书馆。
首先我尝试 https://github.com/AArnott/PCLCrypto但我总是得到:An exception of type 'System.NotImplementedException' occurred in PCLCrypto.dll but was not handled in user code
检查了然后的代码,我看到 PCL 的 Crpyto 没有实现,并且总是抛出异常
然后我找到了这个库:https://github.com/onovotny/BouncyCastle-PCL
但是没有如何使用它的文档。有人可以给我一个如何实施的例子
吗var sha = new HMACSHA256(key)
var sha = new HMACSHA384(key)
var sha = new HMACSHA512(key)
与BouncyCastle-PCL。
尝试这样HmacSha256
public class HmacSha256
{
private readonly HMac _hmac;
public HmacSha256(byte[] key)
{
_hmac = new HMac(new Sha256Digest());
_hmac.Init(new KeyParameter(key));
}
public byte[] ComputeHash(byte[] value)
{
if (value == null) throw new ArgumentNullException("value");
byte[] resBuf = new byte[_hmac.GetMacSize()];
_hmac.BlockUpdate(value, 0, value.Length);
_hmac.DoFinal(resBuf, 0);
return resBuf;
}
}
其他两个应该也是如此...
这只是
一个后续,因为它出现在谷歌上。PCLCrypto 库确实实现了所有哈希方法,但不是在 PCL dll 中。PCL dll 只是一个存根,实际实现位于特定于平台的 DLL 中。
只要确保从所有项目中引用PCLCrypto库,而不仅仅是PCL库。
该技术称为诱饵和开关,之所以使用,是因为它允许最终应用程序利用系统特定的加密 API(以获得更快的性能)
请参阅 https://github.com/AArnott/PCLCrypto#installation