Exemplo n.º 1
0
        internal void Add(byte[] entropy, IEntropySource source)
        {
            // Determine how much of the packet will be accepted.
            _CountOfBytesBySource.TryGetValue(source, out var countFromSource);
            var bytesToaccept = BytesToAcceptFromSource(entropy.Length, countFromSource);

            if (bytesToaccept <= 0)
            {
                // Ignoring this packet entirely.
                return;
            }

            // Accumulate the packer into the hash function.
            // Note that this may only incorporate part of the packet.
            AccumulateBlock(entropy, bytesToaccept);

            // Increment counters. Note that this may overflow for very long lived pools.
            if (_CountOfBytesBySource.Count <= MaxSourcesToCount && countFromSource < Int32.MaxValue)
            {
                try
                {
                    _CountOfBytesBySource[source] = countFromSource + bytesToaccept;
                }
                catch (OverflowException)
                {
                    _CountOfBytesBySource[source] = Int32.MaxValue;
                }
            }
            TotalEntropyBytes           = TotalEntropyBytes + bytesToaccept;
            EntropyBytesSinceLastDigest = EntropyBytesSinceLastDigest + bytesToaccept;
        }
Exemplo n.º 2
0
        public async Task ForceReseed()
        {
            var sources = new IEntropySource[] { new CryptoRandomSource(64), new CurrentTimeSource(), new GCMemorySource(), new TimerSource(), new UserSuppliedSource(CypherBasedPrngGenerator.CreateWithCheapKey().GetRandomBytes(2048)) };
            var acc     = new EntropyAccumulator(new StandardRandomWrapperGenerator());
            var rng     = PooledEntropyCprngGenerator.Create(sources, accumulator: acc, config: Conf());

            Assert.AreEqual(rng.BytesRequested, 0);
            Assert.AreEqual(rng.ReseedCount, 0);
            Assert.AreEqual(rng.IsRunning, false);
            Assert.AreEqual(rng.EntropyPriority, EntropyPriority.High);
            Assert.AreEqual(rng.SourceCount, 5);

            await rng.StartAndWaitForFirstSeed();

            Assert.IsTrue(rng.ReseedCount >= 1);
            Assert.IsTrue(acc.TotalEntropyBytes > 0);
            Assert.AreNotEqual(rng.EntropyPriority, EntropyPriority.High);

            var reseedCount = rng.ReseedCount;
            var entropy     = acc.TotalEntropyBytes;
            await rng.Reseed();

            Assert.IsTrue(rng.ReseedCount > reseedCount);
            Assert.IsTrue(acc.TotalEntropyBytes > entropy);

            await rng.Stop();
        }
Exemplo n.º 3
0
        /**
         * Construct a SP800-90A Hash DRBG.
         * <p>
         * Minimum entropy requirement is the security strength requested.
         * </p>
         * @param digest  source digest to use for DRB stream.
         * @param securityStrength security strength required (in bits)
         * @param entropySource source of entropy to use for seeding/reseeding.
         * @param personalizationString personalization string to distinguish this DRBG (may be null).
         * @param nonce nonce to further distinguish this DRBG (may be null).
         */
        public HashSP800Drbg(IDigest digest, int securityStrength, IEntropySource entropySource, byte[] personalizationString, byte[] nonce)
        {
            if (securityStrength > DrbgUtilities.GetMaxSecurityStrength(digest))
            {
                throw new ArgumentException("Requested security strength is not supported by the derivation function");
            }
            if (entropySource.EntropySize < securityStrength)
            {
                throw new ArgumentException("Not enough entropy for security strength required");
            }

            mDigest           = digest;
            mEntropySource    = entropySource;
            mSecurityStrength = securityStrength;
            mSeedLength       = (int)seedlens[digest.AlgorithmName];

            // 1. seed_material = entropy_input || nonce || personalization_string.
            // 2. seed = Hash_df (seed_material, seedlen).
            // 3. V = seed.
            // 4. C = Hash_df ((0x00 || V), seedlen). Comment: Preceed V with a byte
            // of zeros.
            // 5. reseed_counter = 1.
            // 6. Return V, C, and reseed_counter as the initial_working_state

            byte[] entropy      = GetEntropy();
            byte[] seedMaterial = Arrays.ConcatenateAll(entropy, nonce, personalizationString);
            byte[] seed         = DrbgUtilities.HashDF(mDigest, seedMaterial, mSeedLength);

            mV = seed;
            byte[] subV = new byte[mV.Length + 1];
            Array.Copy(mV, 0, subV, 1, mV.Length);
            mC = DrbgUtilities.HashDF(mDigest, subV, mSeedLength);

            mReseedCounter = 1;
        }
Exemplo n.º 4
0
        /**
	     * Construct a SP800-90A Hash DRBG.
	     * <p>
	     * Minimum entropy requirement is the security strength requested.
	     * </p>
	     * @param digest  source digest to use for DRB stream.
	     * @param securityStrength security strength required (in bits)
	     * @param entropySource source of entropy to use for seeding/reseeding.
	     * @param personalizationString personalization string to distinguish this DRBG (may be null).
	     * @param nonce nonce to further distinguish this DRBG (may be null).
	     */
	    public HashSP800Drbg(IDigest digest, int securityStrength, IEntropySource entropySource, byte[] personalizationString, byte[] nonce)
	    {
	        if (securityStrength > DrbgUtilities.GetMaxSecurityStrength(digest))
	            throw new ArgumentException("Requested security strength is not supported by the derivation function");
	        if (entropySource.EntropySize < securityStrength)
	            throw new ArgumentException("Not enough entropy for security strength required");

            mDigest = digest;
	        mEntropySource = entropySource;
	        mSecurityStrength = securityStrength;
            mSeedLength = (int)seedlens[digest.AlgorithmName];

            // 1. seed_material = entropy_input || nonce || personalization_string.
	        // 2. seed = Hash_df (seed_material, seedlen).
	        // 3. V = seed.
	        // 4. C = Hash_df ((0x00 || V), seedlen). Comment: Preceed V with a byte
	        // of zeros.
	        // 5. reseed_counter = 1.
	        // 6. Return V, C, and reseed_counter as the initial_working_state

	        byte[] entropy = GetEntropy();
	        byte[] seedMaterial = Arrays.ConcatenateAll(entropy, nonce, personalizationString);
	        byte[] seed = DrbgUtilities.HashDF(mDigest, seedMaterial, mSeedLength);

            mV = seed;
	        byte[] subV = new byte[mV.Length + 1];
	        Array.Copy(mV, 0, subV, 1, mV.Length);
	        mC = DrbgUtilities.HashDF(mDigest, subV, mSeedLength);

            mReseedCounter = 1;
	    }
Exemplo n.º 5
0
        public async Task CreatePrngFromPooled()
        {
            var sources = new IEntropySource[] { new CryptoRandomSource(64), new CurrentTimeSource(), new GCMemorySource(), new TimerSource(), new UserSuppliedSource(CypherBasedPrngGenerator.CreateWithCheapKey().GetRandomBytes(2048)) };
            var acc     = new EntropyAccumulator(new StandardRandomWrapperGenerator());
            var rng     = PooledEntropyCprngGenerator.Create(sources, accumulator: acc, config: Conf());

            Assert.AreEqual(rng.BytesRequested, 0);
            Assert.AreEqual(rng.ReseedCount, 0);
            Assert.AreEqual(rng.IsRunning, false);
            Assert.AreEqual(rng.EntropyPriority, EntropyPriority.High);
            Assert.AreEqual(rng.SourceCount, 5);

            await rng.StartAndWaitForFirstSeed();

            Assert.IsTrue(rng.ReseedCount >= 1);
            Assert.IsTrue(acc.TotalEntropyBytes > 0);
            System.Threading.Thread.Sleep(1);           // EntropyPriority is only updated after the reseed event, so it might not be current.
            Assert.AreNotEqual(rng.EntropyPriority, EntropyPriority.High);

            var prng = rng.CreateCypherBasedGenerator();

            Assert.IsNotNull(prng);

            var bytes = prng.GetRandomBytes(16);

            Assert.IsFalse(bytes.All(b => b == 0));

            await rng.Stop();
        }
Exemplo n.º 6
0
        public SourceAndMetadata(IEntropySource source, string uniqueName)
        {
            Source     = source ?? throw new ArgumentNullException(nameof(source));
            UniqueName = uniqueName ?? throw new ArgumentNullException(nameof(uniqueName));
#if NETSTANDARD1_3
            AsyncHint = IsAsync.Unknown;
#else
            var maybeHintAttribute = source.GetType().GetCustomAttributesData().FirstOrDefault(x => x.AttributeType == typeof(AsyncHintAttribute));
            if (maybeHintAttribute != null)
            {
                AsyncHint = (IsAsync)maybeHintAttribute.ConstructorArguments.First(x => x.ArgumentType == typeof(IsAsync)).Value;
            }
#endif
            if (AsyncHint == IsAsync.AfterInit)
            {
                AsyncScore = -8;
            }
            else if (AsyncHint == IsAsync.Never)
            {
                AsyncScore = -10;
            }
            else if (AsyncHint == IsAsync.Rarely)
            {
                AsyncScore = 5;
            }
            else
            {
                AsyncScore = 10;
            }
        }
Exemplo n.º 7
0
        /**
         * Construct a SP800-90A Hash DRBG.
         * <p>
         * Minimum entropy requirement is the security strength requested.
         * </p>
         * @param hMac Hash MAC to base the DRBG on.
         * @param securityStrength security strength required (in bits)
         * @param entropySource source of entropy to use for seeding/reseeding.
         * @param personalizationString personalization string to distinguish this DRBG (may be null).
         * @param nonce nonce to further distinguish this DRBG (may be null).
         */
        public HMacSP800Drbg(IMac hMac, int securityStrength, IEntropySource entropySource, byte[] personalizationString, byte[] nonce)
        {
            if (securityStrength > DrbgUtilities.GetMaxSecurityStrength(hMac))
            {
                throw new ArgumentException("Requested security strength is not supported by the derivation function");
            }
            if (entropySource.EntropySize < securityStrength)
            {
                throw new ArgumentException("Not enough entropy for security strength required");
            }

            mHMac             = hMac;
            mSecurityStrength = securityStrength;
            mEntropySource    = entropySource;

            byte[] entropy      = GetEntropy();
            byte[] seedMaterial = Arrays.ConcatenateAll(entropy, nonce, personalizationString);

            mK = new byte[hMac.GetMacSize()];
            mV = new byte[mK.Length];
            Arrays.Fill(mV, (byte)1);

            hmac_DRBG_Update(seedMaterial);

            mReseedCounter = 1;
        }
Exemplo n.º 8
0
        /**
         * Construct a SP800-90A CTR DRBG.
         * <p>
         * Minimum entropy requirement is the security strength requested.
         * </p>
         * @param engine underlying block cipher to use to support DRBG
         * @param keySizeInBits size of the key to use with the block cipher.
         * @param securityStrength security strength required (in bits)
         * @param entropySource source of entropy to use for seeding/reseeding.
         * @param personalizationString personalization string to distinguish this DRBG (may be null).
         * @param nonce nonce to further distinguish this DRBG (may be null).
         */
        public CtrSP800Drbg(IBlockCipher engine, int keySizeInBits, int securityStrength, IEntropySource entropySource,
                            byte[] personalizationString, byte[] nonce)
        {
            if (securityStrength > 256)
            {
                throw new ArgumentException("Requested security strength is not supported by the derivation function");
            }
            if (GetMaxSecurityStrength(engine, keySizeInBits) < securityStrength)
            {
                throw new ArgumentException("Requested security strength is not supported by block cipher and key size");
            }
            if (entropySource.EntropySize < securityStrength)
            {
                throw new ArgumentException("Not enough entropy for security strength required");
            }

            mEntropySource = entropySource;
            mEngine        = engine;

            mKeySizeInBits    = keySizeInBits;
            mSecurityStrength = securityStrength;
            mSeedLength       = keySizeInBits + engine.GetBlockSize() * 8;
            mIsTdea           = IsTdea(engine);

            byte[] entropy = GetEntropy();      // Get_entropy_input

            CTR_DRBG_Instantiate_algorithm(entropy, nonce, personalizationString);
        }
Exemplo n.º 9
0
 internal SP800SecureRandom(SecureRandom randomSource, IEntropySource entropySource, IDrbgProvider drbgProvider, bool predictionResistant)
     : base((IRandomGenerator)null)
 {
     this.mRandomSource = randomSource;
     this.mEntropySource = entropySource;
     this.mDrbgProvider = drbgProvider;
     this.mPredictionResistant = predictionResistant;
 }
Exemplo n.º 10
0
 internal SP800SecureRandom(SecureRandom randomSource, IEntropySource entropySource, IDrbgProvider drbgProvider, bool predictionResistant)
     : base((IRandomGenerator)null)
 {
     this.mRandomSource        = randomSource;
     this.mEntropySource       = entropySource;
     this.mDrbgProvider        = drbgProvider;
     this.mPredictionResistant = predictionResistant;
 }
Exemplo n.º 11
0
 internal X931Rng(IBlockCipher engine, byte[] dateTimeVector, IEntropySource entropySource)
 {
     mEngine        = engine;
     mEntropySource = entropySource;
     mDT            = new byte[engine.GetBlockSize()];
     Array.Copy(dateTimeVector, 0, mDT, 0, mDT.Length);
     mI = new byte[engine.GetBlockSize()];
     mR = new byte[engine.GetBlockSize()];
 }
Exemplo n.º 12
0
 public DRBGTestVector(IDigest digest, IEntropySource eSource, bool predictionResistance, String nonce, int securityStrength, byte[][] expected)
 {
     _digest          = digest;
     _eSource         = eSource;
     _pr              = predictionResistance;
     _nonce           = nonce;
     _ss              = securityStrength;
     _ev              = expected;
     _personalisation = null;
 }
Exemplo n.º 13
0
 public DrbgTestVector(IDigest digest, IEntropySource eSource, bool predictionResistance, string nonce,
     int securityStrength, string[] expected)
 {
     _digest = digest;
     _eSource = eSource;
     _pr = predictionResistance;
     _nonce = nonce;
     _ss = securityStrength;
     _ev = expected;
     _personalisation = null;
 }
Exemplo n.º 14
0
 public DRBGTestVector(Org.BouncyCastle.Crypto.Internal.IBlockCipher cipher, int keySizeInBits, IEntropySource eSource, bool predictionResistance, String nonce, int securityStrength, byte[][] expected)
 {
     _cipher          = cipher;
     _keySizeInBits   = keySizeInBits;
     _eSource         = eSource;
     _pr              = predictionResistance;
     _nonce           = nonce;
     _ss              = securityStrength;
     _ev              = expected;
     _personalisation = null;
 }
Exemplo n.º 15
0
        public void ConstructMinimal()
        {
            var sources = new IEntropySource[] { new NullSource(), new NullSource() };
            var rng     = new PooledEntropyCprngGenerator(sources);

            // Creating a generator should not actually generate any bytes or even start the generator.
            Assert.AreEqual(rng.BytesRequested, 0);
            Assert.AreEqual(rng.ReseedCount, 0);
            Assert.AreEqual(rng.IsRunning, false);
            Assert.AreEqual(rng.EntropyPriority, EntropyPriority.High);
        }
Exemplo n.º 16
0
        /**
         *
         * @param engine
         * @param entropySource
         */
        internal X931Rng(IBlockCipher engine, byte[] dateTimeVector, IEntropySource entropySource)
        {
            this.mEngine = engine;
            this.mEntropySource = entropySource;

            this.mDT = new byte[engine.GetBlockSize()];

            Array.Copy(dateTimeVector, 0, mDT, 0, mDT.Length);

            this.mI = new byte[engine.GetBlockSize()];
            this.mR = new byte[engine.GetBlockSize()];
        }
Exemplo n.º 17
0
 public DrbgTestVector(IBlockCipher cipher, int keySizeInBits, IEntropySource eSource, bool predictionResistance,
                       string nonce, int securityStrength, string[] expected)
 {
     _cipher          = cipher;
     _keySizeInBits   = keySizeInBits;
     _eSource         = eSource;
     _pr              = predictionResistance;
     _nonce           = nonce;
     _ss              = securityStrength;
     _ev              = expected;
     _personalisation = null;
 }
Exemplo n.º 18
0
        public async Task PooledGenerator()
        {
            var sources = new IEntropySource[] { new CryptoRandomSource(64), new CurrentTimeSource(), new GCMemorySource(), new NetworkStatsSource(), new ProcessStatsSource(), new TimerSource() };
            var acc     = new EntropyAccumulator(new StandardRandomWrapperGenerator());
            var rng     = new PooledEntropyCprngGenerator(sources, acc);

            await rng.StartAndWaitForFirstSeed();

            await FuzzGenerator(10000, 1, 64, rng, nameof(PooledEntropyCprngGenerator));

            await rng.Stop();
        }
Exemplo n.º 19
0
        public void ConstructWithPrng()
        {
            var sources = new IEntropySource[] { new NullSource(), new NullSource() };
            var prng    = new CypherBasedPrngGenerator(new StandardRandomWrapperGenerator().GetRandomBytes(32));
            var rng     = new PooledEntropyCprngGenerator(sources, prng);

            // Creating a generator should not actually generate any bytes or even start the generator.
            Assert.AreEqual(rng.BytesRequested, 0);
            Assert.AreEqual(rng.ReseedCount, 0);
            Assert.AreEqual(rng.IsRunning, false);
            Assert.AreEqual(rng.EntropyPriority, EntropyPriority.High);
        }
Exemplo n.º 20
0
 public DrbgTestVector(IBlockCipher cipher, int keySizeInBits, IEntropySource eSource, bool predictionResistance,
     string nonce, int securityStrength, string[] expected)
 {
     _cipher = cipher;
     _keySizeInBits = keySizeInBits;
     _eSource = eSource;
     _pr = predictionResistance;
     _nonce = nonce;
     _ss = securityStrength;
     _ev = expected;
     _personalisation = null;
 }
Exemplo n.º 21
0
        public void ConstructWithLocalSources()
        {
            var sources = new IEntropySource[] { new CryptoRandomSource(), new CurrentTimeSource(), new GCMemorySource(), new NetworkStatsSource(), new ProcessStatsSource(), new TimerSource() };
            var rng     = new PooledEntropyCprngGenerator(sources);

            // Creating a generator should not actually generate any bytes or even start the generator.
            Assert.AreEqual(rng.BytesRequested, 0);
            Assert.AreEqual(rng.ReseedCount, 0);
            Assert.AreEqual(rng.IsRunning, false);
            Assert.AreEqual(rng.EntropyPriority, EntropyPriority.High);
            Assert.AreEqual(rng.SourceCount, 6);
        }
Exemplo n.º 22
0
 /**
  * Generate numBytes worth of entropy from the passed in entropy source.
  *
  * @param entropySource the entropy source to request the data from.
  * @param numBytes the number of bytes of entropy requested.
  * @return a byte array populated with the random data.
  */
 public static byte[] GenerateSeed(IEntropySource entropySource, int numBytes)
 {
     byte[] bytes = new byte[numBytes];
     int count = 0;
     while (count < numBytes)
     {
         byte[] entropy = entropySource.GetEntropy();
         int toCopy = System.Math.Min(bytes.Length, numBytes - count);
         Array.Copy(entropy, 0, bytes, count, toCopy);
         count += toCopy;
     }
     return bytes;
 }
Exemplo n.º 23
0
    public static byte[] GenerateSeed(IEntropySource entropySource, int numBytes)
    {
        byte[] array = new byte[numBytes];
        int    num;

        for (int i = 0; i < numBytes; i += num)
        {
            byte[] entropy = entropySource.GetEntropy();
            num = Math.Min(array.Length, numBytes - i);
            Array.Copy(entropy, 0, array, i, num);
        }
        return(array);
    }
Exemplo n.º 24
0
        /**
         * Generate numBytes worth of entropy from the passed in entropy source.
         *
         * @param entropySource the entropy source to request the data from.
         * @param numBytes the number of bytes of entropy requested.
         * @return a byte array populated with the random data.
         */
        public static byte[] GenerateSeed(IEntropySource entropySource, int numBytes)
        {
            byte[] bytes = new byte[numBytes];
            int    count = 0;

            while (count < numBytes)
            {
                byte[] entropy = entropySource.GetEntropy();
                int    toCopy  = System.Math.Min(bytes.Length, numBytes - count);
                Array.Copy(entropy, 0, bytes, count, toCopy);
                count += toCopy;
            }
            return(bytes);
        }
Exemplo n.º 25
0
        public async Task EventIsRaisedOnReseed()
        {
            var    sources          = new IEntropySource[] { new CryptoRandomSource(64), new CurrentTimeSource(), new GCMemorySource(), new TimerSource(), new UserSuppliedSource(CypherBasedPrngGenerator.CreateWithCheapKey().GetRandomBytes(2048)) };
            var    acc              = new EntropyAccumulator(new StandardRandomWrapperGenerator());
            var    rng              = PooledEntropyCprngGenerator.Create(sources, accumulator: acc, config: Conf());
            Object setInReseedEvent = null;

            rng.OnReseed += (o, e) => setInReseedEvent = new object();
            Assert.AreEqual(rng.BytesRequested, 0);
            Assert.AreEqual(rng.ReseedCount, 0);
            Assert.AreEqual(rng.IsRunning, false);
            Assert.AreEqual(rng.EntropyPriority, EntropyPriority.High);
            Assert.AreEqual(rng.SourceCount, 5);

            await rng.StartAndWaitForFirstSeed();

            Assert.IsNotNull(setInReseedEvent);

            await rng.Stop();
        }
Exemplo n.º 26
0
        /// <summary>
        /// Adds a new Entropy Source to the Poller.
        /// </summary>
        /// <param name="source">The EntropySource object to add.</param>
        public void AddEntropySource(IEntropySource source)
        {
            lock (EntropySources)
                EntropySources.Add(source);

            AddEntropy(source.GetPrimer());
            MixPool();

            //Apply "whitening" effect. Try to mix the pool using RIPEMD-160 to strengthen
            //the cryptographic strength of the pool.
            //There is a need to catch the InvalidOperationException because if Eraser is
            //running under an OS with FIPS-compliance mode the RIPEMD-160 algorithm cannot
            //be used.
            HashAlgorithm secondaryHash = GetSecondaryHash();

            if (secondaryHash != null)
            {
                MixPool(secondaryHash);
            }
        }
Exemplo n.º 27
0
        public async Task GetFirstSeed_MixedSyncAndAsyncSources()
        {
            var sources = new IEntropySource[] { new CryptoRandomSource(32), new CurrentTimeSource(), new GCMemorySource(), new TimerSource(), new AsyncCryptoRandomSource(), new ProcessStatsSource(), new NetworkStatsSource() };
            var acc     = new EntropyAccumulator(new StandardRandomWrapperGenerator());
            var rng     = PooledEntropyCprngGenerator.Create(sources, accumulator: acc, config: Conf());

            Assert.AreEqual(rng.BytesRequested, 0);
            Assert.AreEqual(rng.ReseedCount, 0);
            Assert.AreEqual(rng.IsRunning, false);
            Assert.AreEqual(rng.EntropyPriority, EntropyPriority.High);
            Assert.AreEqual(rng.SourceCount, 7);

            await rng.StartAndWaitForFirstSeed();

            Assert.IsTrue(rng.ReseedCount >= 1);
            Assert.IsTrue(acc.TotalEntropyBytes > 0);
            System.Threading.Thread.Sleep(1);           // EntropyPriority is only updated after the reseed event, so it might not be current.
            Assert.AreNotEqual(rng.EntropyPriority, EntropyPriority.High);

            await rng.Stop();
        }
Exemplo n.º 28
0
 public HashSP800Drbg(IDigest digest, int securityStrength, IEntropySource entropySource, byte[] personalizationString, byte[] nonce)
 {
     if (securityStrength > DrbgUtilities.GetMaxSecurityStrength(digest))
     {
         throw new ArgumentException("Requested security strength is not supported by the derivation function");
     }
     if (entropySource.EntropySize < securityStrength)
     {
         throw new ArgumentException("Not enough entropy for security strength required");
     }
     mDigest           = digest;
     mEntropySource    = entropySource;
     mSecurityStrength = securityStrength;
     mSeedLength       = (int)seedlens[digest.AlgorithmName];
     byte[] entropy      = GetEntropy();
     byte[] seedMaterial = Arrays.ConcatenateAll(entropy, nonce, personalizationString);
     byte[] array        = mV = DrbgUtilities.HashDF(mDigest, seedMaterial, mSeedLength);
     byte[] array2       = new byte[mV.Length + 1];
     Array.Copy(mV, 0, array2, 1, mV.Length);
     mC             = DrbgUtilities.HashDF(mDigest, array2, mSeedLength);
     mReseedCounter = 1L;
 }
Exemplo n.º 29
0
	    /**
	     * Construct a SP800-90A CTR DRBG.
	     * <p>
	     * Minimum entropy requirement is the security strength requested.
	     * </p>
	     * @param engine underlying block cipher to use to support DRBG
	     * @param keySizeInBits size of the key to use with the block cipher.
	     * @param securityStrength security strength required (in bits)
	     * @param entropySource source of entropy to use for seeding/reseeding.
	     * @param personalizationString personalization string to distinguish this DRBG (may be null).
	     * @param nonce nonce to further distinguish this DRBG (may be null).
	     */
	    public CtrSP800Drbg(IBlockCipher engine, int keySizeInBits, int securityStrength, IEntropySource entropySource,
            byte[] personalizationString, byte[] nonce)
	    {
	        if (securityStrength > 256)
	            throw new ArgumentException("Requested security strength is not supported by the derivation function");
	        if (GetMaxSecurityStrength(engine, keySizeInBits) < securityStrength)
	            throw new ArgumentException("Requested security strength is not supported by block cipher and key size");
	        if (entropySource.EntropySize < securityStrength)
	            throw new ArgumentException("Not enough entropy for security strength required");

            mEntropySource = entropySource;
	        mEngine = engine;     

            mKeySizeInBits = keySizeInBits;
	        mSecurityStrength = securityStrength;
	        mSeedLength = keySizeInBits + engine.GetBlockSize() * 8;
	        mIsTdea = IsTdea(engine);

	        byte[] entropy = GetEntropy();  // Get_entropy_input

            CTR_DRBG_Instantiate_algorithm(entropy, nonce, personalizationString);
	    }
Exemplo n.º 30
0
        /**
	     * Construct a SP800-90A Hash DRBG.
	     * <p>
	     * Minimum entropy requirement is the security strength requested.
	     * </p>
	     * @param hMac Hash MAC to base the DRBG on.
	     * @param securityStrength security strength required (in bits)
	     * @param entropySource source of entropy to use for seeding/reseeding.
	     * @param personalizationString personalization string to distinguish this DRBG (may be null).
	     * @param nonce nonce to further distinguish this DRBG (may be null).
	     */
	    public HMacSP800Drbg(IMac hMac, int securityStrength, IEntropySource entropySource, byte[] personalizationString, byte[] nonce)
	    {
	        if (securityStrength > DrbgUtilities.GetMaxSecurityStrength(hMac))
	            throw new ArgumentException("Requested security strength is not supported by the derivation function");
	        if (entropySource.EntropySize < securityStrength)
	            throw new ArgumentException("Not enough entropy for security strength required");

            mHMac = hMac;
            mSecurityStrength = securityStrength;
	        mEntropySource = entropySource;

            byte[] entropy = GetEntropy();
	        byte[] seedMaterial = Arrays.ConcatenateAll(entropy, nonce, personalizationString);

            mK = new byte[hMac.GetMacSize()];
	        mV = new byte[mK.Length];
	        Arrays.Fill(mV, (byte)1);

            hmac_DRBG_Update(seedMaterial);

            mReseedCounter = 1;
	    }
Exemplo n.º 31
0
        private async Task FuzzEntropySource(int iterations, IEntropySource source, string filename, Action extra)
        {
            using (var sw = new StreamWriter(filename + ".txt", false, Encoding.UTF8))
            {
                await sw.WriteLineAsync($"{source.GetType().FullName} - {iterations:N0} iterations");

                for (int i = 0; i < iterations; i++)
                {
                    var bytes = await source.GetEntropyAsync(EntropyPriority.High);

                    if (bytes == null)
                    {
                        await sw.WriteLineAsync("<null>");
                    }
                    else
                    {
                        await sw.WriteLineAsync(bytes.ToHexString());
                    }
                    extra();
                }
            }
        }
Exemplo n.º 32
0
        private void init(int securityStrength, IEntropySource entropySource, byte[] personalizationString, byte[] nonce)
        {
            if (securityStrength > 256)
            {
                throw new ArgumentException("Requested security strength is not supported by the derivation function");
            }

            if (getMaxSecurityStrength(mEngine, mKeySizeInBits) < securityStrength)
            {
                throw new ArgumentException("Requested security strength is not supported by the derivation function");
            }

            if (entropySource.EntropySize < securityStrength)
            {
                throw new ArgumentException("Not enough entropy for security strength required");
            }

            mEntropySource    = entropySource;
            mSecurityStrength = securityStrength;

            CTR_DRBG_Instantiate_algorithm(personalizationString, nonce);
        }
Exemplo n.º 33
0
 public HashSP800Drbg(IDigest digest, int securityStrength, IEntropySource entropySource, byte[] personalizationString, byte[] nonce)
 {
     //IL_0014: Unknown result type (might be due to invalid IL or missing references)
     //IL_0028: Unknown result type (might be due to invalid IL or missing references)
     if (securityStrength > DrbgUtilities.GetMaxSecurityStrength(digest))
     {
         throw new ArgumentException("Requested security strength is not supported by the derivation function");
     }
     if (entropySource.EntropySize < securityStrength)
     {
         throw new ArgumentException("Not enough entropy for security strength required");
     }
     mDigest           = digest;
     mEntropySource    = entropySource;
     mSecurityStrength = securityStrength;
     mSeedLength       = (int)seedlens.get_Item((object)digest.AlgorithmName);
     byte[] entropy      = GetEntropy();
     byte[] seedMaterial = Arrays.ConcatenateAll(entropy, nonce, personalizationString);
     byte[] array        = (mV = DrbgUtilities.HashDF(mDigest, seedMaterial, mSeedLength));
     byte[] array2       = new byte[mV.Length + 1];
     global::System.Array.Copy((global::System.Array)mV, 0, (global::System.Array)array2, 1, mV.Length);
     mC             = DrbgUtilities.HashDF(mDigest, array2, mSeedLength);
     mReseedCounter = 1L;
 }
Exemplo n.º 34
0
        public async Task FirstSeedYieldsDifferentBytes()
        {
            var sources = new IEntropySource[] { new CryptoRandomSource(64), new CurrentTimeSource(), new GCMemorySource(), new TimerSource(), new UserSuppliedSource(CypherBasedPrngGenerator.CreateWithCheapKey().GetRandomBytes(2048)) };
            var acc1    = new EntropyAccumulator(new StandardRandomWrapperGenerator());
            var rng1    = PooledEntropyCprngGenerator.Create(sources, accumulator: acc1, config: Conf());
            await rng1.StartAndWaitForFirstSeed();

            var acc2 = new EntropyAccumulator(new StandardRandomWrapperGenerator());
            var rng2 = PooledEntropyCprngGenerator.Create(sources, accumulator: acc2, config: Conf());
            await rng2.StartAndWaitForFirstSeed();

            var bytesFrom1 = rng1.GetRandomBytes(64);

            Assert.IsFalse(bytesFrom1.All(b => b == 0));
            var bytesFrom2 = rng2.GetRandomBytes(64);

            Assert.IsFalse(bytesFrom2.All(b => b == 0));
            // Expect two generates with different inputs will give different bytes from from the start.
            Assert.IsFalse(bytesFrom1.SequenceEqual(bytesFrom2));

            await rng1.Stop();

            await rng2.Stop();
        }
 public ISP80090Drbg Get(IEntropySource entropySource)
 {
     return new CtrSP800Drbg(mBlockCipher, mKeySizeInBits, mSecurityStrength, entropySource, mPersonalizationString, mNonce);
 }
 public ISP80090Drbg Get(IEntropySource entropySource)
 {
     return new HMacSP800Drbg(mHMac, mSecurityStrength, entropySource, mPersonalizationString, mNonce);
 }
 public ISP80090Drbg Get(IEntropySource entropySource)
 {
     return(new CtrSP800Drbg(mBlockCipher, mKeySizeInBits, mSecurityStrength, entropySource, mPersonalizationString, mNonce));
 }
 public ISP80090Drbg Get(IEntropySource entropySource)
 {
     return(new HMacSP800Drbg(mHMac, mSecurityStrength, entropySource, mPersonalizationString, mNonce));
 }
Exemplo n.º 39
0
 internal DrbgPseudoRandom(Algorithm algorithm, IEntropySource entropySource, IDrbgProvider drbgProvider)
 {
     this.algorithm     = algorithm;
     this.entropySource = new ContinuousTestingEntropySource(entropySource);
     this.drbgProvider  = drbgProvider;
 }
Exemplo n.º 40
0
            internal override void Evaluate()
            {
                byte[]         origV                = parent.mV;
                byte[]         origC                = parent.mC;
                long           origReseedCounter    = parent.mReseedCounter;
                IEntropySource origEntropySource    = parent.mEntropySource;
                int            origSeedLength       = parent.mSeedLength;
                int            origSecurityStrength = parent.mSecurityStrength;

                try
                {
                    byte[] additionalInput = Hex.Decode("404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F606162636465666768696A6B6C6D6E6F70717273747576");

                    int entropyStrength = DrbgUtilities.GetMaxSecurityStrength(parent.mDigest);

                    byte[][] expected = (byte[][])reseedKats[algorithm.Name];

                    parent.mV = Arrays.Clone((byte[])reseedVs[algorithm.Name]);

                    parent.mEntropySource = new DrbgUtilities.KatEntropyProvider().Get(entropyStrength);

                    parent.Reseed(additionalInput);

                    if (parent.mReseedCounter != 1)
                    {
                        Fail("DRBG reseedCounter failed to reset");
                    }

                    byte[] output = new byte[expected[0].Length];

                    parent.Generate(output, null, false);
                    if (!Arrays.AreEqual(expected[0], output))
                    {
                        Fail("DRBG Block 1 reseed KAT failure");
                    }

                    output = new byte[expected[1].Length];

                    parent.Generate(output, null, false);
                    if (!Arrays.AreEqual(expected[1], output))
                    {
                        Fail("DRBG Block 2 reseed KAT failure");
                    }

                    try
                    {
                        parent.mEntropySource = new DrbgUtilities.LyingEntropySource(entropyStrength);

                        parent.Reseed(null);

                        Fail("DRBG LyingEntropySource not detected on reseed");
                    }
                    catch (InvalidOperationException e)
                    {
                        if (!e.Message.Equals("Insufficient entropy provided by entropy source"))
                        {
                            Fail("DRBG self test failed reseed entropy check");
                        }
                    }
                }
                finally
                {
                    parent.mV                = origV;
                    parent.mC                = origC;
                    parent.mReseedCounter    = origReseedCounter;
                    parent.mEntropySource    = origEntropySource;
                    parent.mSeedLength       = origSeedLength;
                    parent.mSecurityStrength = origSecurityStrength;
                }
            }