BouncyCastle.NetCore:无法找到CryptoApiRandomGenerator类

时间:2017-05-16 13:37:44

标签: .net-core bouncycastle

我已经安装了BouncyCastle.NetCore软件包以创建自签名证书,但我找不到 CryptoApiRandomGenerator 类。

这是正常的吗?如果是,替代品是什么?

2 个答案:

答案 0 :(得分:1)

您可以实现自己的CryptoApiRandomGenerator。 像这样:

public class MyCryptoApiRandomGenerator
    : IRandomGenerator
{
    private readonly RNGCryptoServiceProvider rndProv;

    public NetMatchCryptoApiRandomGenerator()
    {
        rndProv = new RNGCryptoServiceProvider();
    }

    #region IRandomGenerator Members

    public virtual void AddSeedMaterial(byte[] seed)
    {
        // I don't care about the seed
    }

    public virtual void AddSeedMaterial(long seed)
    {
        // I don't care about the seed
    }

    public virtual void NextBytes(byte[] bytes)
    {
        rndProv.GetBytes(bytes);
    }

    public virtual void NextBytes(byte[] bytes, int start, int len)
    {
        if (start < 0)
            throw new ArgumentException("Start offset cannot be negative", "start");
        if (bytes.Length < (start + len))
            throw new ArgumentException("Byte array too small for requested offset and length");

        if (bytes.Length == len && start == 0)
        {
            NextBytes(bytes);
        }
        else
        {
            byte[] tmpBuf = new byte[len];
            rndProv.GetBytes(tmpBuf);
            Array.Copy(tmpBuf, 0, bytes, start, len);
        }
    }

    #endregion
}

.Net Core中目前没有隐式实现。

答案 1 :(得分:0)

如果您使用“ reflector”或“ just decompile”反编译CryptoApiRandomGenerator类,则Andrei Ardel拥有权利,您会找到可以添加到项目中的实现:

public class CryptoApiRandomGenerator : IRandomGenerator
    {
        private readonly RandomNumberGenerator rndProv;

        public CryptoApiRandomGenerator() : this(new RNGCryptoServiceProvider())
        {
        }

        public CryptoApiRandomGenerator(RandomNumberGenerator rng)
        {
            this.rndProv = rng;
        }

        public virtual void AddSeedMaterial(byte[] seed)
        {
        }

        public virtual void AddSeedMaterial(long seed)
        {
        }

        public virtual void NextBytes(byte[] bytes)
        {
            this.rndProv.GetBytes(bytes);
        }

        public virtual void NextBytes(byte[] bytes, int start, int len)
        {
            if (start < 0)
            {
                throw new ArgumentException("Start offset cannot be negative", "start");
            }
            if ((int)bytes.Length < start + len)
            {
                throw new ArgumentException("Byte array too small for requested offset and length");
            }
            if ((int)bytes.Length == len && start == 0)
            {
                this.NextBytes(bytes);
                return;
            }
            byte[] numArray = new byte[len];
            this.NextBytes(numArray);
            Array.Copy(numArray, 0, bytes, start, len);
        }
    }