C# PCL HMACSHAX with BouncyCastle-PCL

早过忘川 提交于 2020-01-02 18:07:34

问题


I want to implement this logic in portable C# class:

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

but HMACSHA256, HMACSHA384 and HMACSHA512 does not exist in portable library.

First I try with https://github.com/AArnott/PCLCrypto but I always get: An exception of type 'System.NotImplementedException' occurred in PCLCrypto.dll but was not handled in user code

I checked then code and I saw Crpyto for PCL is not implemented and always throw an exception

Then i found this library: https://github.com/onovotny/BouncyCastle-PCL

But there is no documentation how to use it. Can someone give me an exmaple how to implement

var sha = new HMACSHA256(key)
var sha = new HMACSHA384(key)
var sha = new HMACSHA512(key)

with BouncyCastle-PCL.


回答1:


Try like this for 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;
        }
    }

The same should be for other two...




回答2:


This is just a follow up because it shows up on Google. The PCLCrypto Library does implement all the hash methods, but not in the PCL dll. The PCL dll is only a stub, and the actual implementations are in the platform specific DLLs.

Just make sure you reference the PCLCrypto library from ALL your projects, and not just the PCL library.

The technique is called bait-and-switch and is used because it allows for the end application to utilize the system specific crypto apis (for faster performance)

See https://github.com/AArnott/PCLCrypto#installation



来源:https://stackoverflow.com/questions/30974846/c-sharp-pcl-hmacshax-with-bouncycastle-pcl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!