示例#1
0
        private void doExpectedTest(IDigest digest, int seed, byte[] expected, byte[] noCycle)
        {
            DigestRandomGenerator rGen = new DigestRandomGenerator(digest);

            byte[] output = new byte[digest.GetDigestSize()];

            rGen.AddSeedMaterial(seed);

            for (int i = 0; i != 1024; i++)
            {
                rGen.NextBytes(output);
            }

            if (noCycle != null)
            {
                if (Arrays.AreEqual(noCycle, output))
                {
                    Fail("seed not being cycled!");
                }
            }

            if (!Arrays.AreEqual(expected, output))
            {
                Fail("expected output doesn't match");
            }
        }
        public void NextBytesSpan()
        {
            Span <byte> buffer = stackalloc byte[20];

            using DigestRandomGenerator generator = new DigestRandomGenerator(HashAlgorithmName.SHA1);
            generator.NextBytes(buffer);
        }
        /// <summary>
        /// Gets the <see cref="SecureRandom"/> instance based on our <see cref="IDigest"/> and seed data.
        /// </summary>
        /// <param name="randomDigest"> The algorithm to use to use for random processing. </param>
        /// <param name="seedData"> Array of objects to use as our random seed. </param>
        /// <returns> The <see cref="SecureRandom"/> created from our <see cref="IDigest"/> and seed. </returns>
        private SecureRandom GetSecureRandom(IDigest randomDigest, object[] seedData)
        {
            IRandomGenerator randomGenerator = new DigestRandomGenerator(randomDigest);

            if (seedData == null || seedData.Length == 0)
            {
                randomGenerator.AddSeedMaterial(SecureRandom.GetNextBytes(new SecureRandom(), 16));
            }
            else
            {
                foreach (var seed in seedData)
                {
                    Type   seedType = seed.GetType();
                    byte[] byteData = seedType == typeof(byte[])
                        ? (byte[])seed
                        : seed is IRandomSeed
                            ? ((IRandomSeed)seed).Seed
                            : Encoding.UTF8.GetBytes(seed.ToString());

                    randomGenerator.AddSeedMaterial(byteData);
                }
            }

            return(new SecureRandom(randomGenerator));
        }
示例#4
0
        public CSPRNGServer()
        {
            Console.WriteLine(Directory.GetCurrentDirectory());

            //the CSPRNG is seeded using a thread based seed generator in BC
            byte[] seedarray = new byte[512];
            digest = new Sha512Digest();
            gen    = new DigestRandomGenerator(digest);


            //add some additional entropy to the seed
            for (int i = 0; i < 48; i++)
            {
                gen.AddSeedMaterial(DateTime.Now.Ticks);
            }

            int threadId = System.Threading.Thread.CurrentThread.ManagedThreadId;

            gen.AddSeedMaterial(threadId);

            instcheck++;

            secp256k1 = new secp256k1Wrap();


            //load database commands from files
        }
示例#5
0
        /// <summary>
        /// Returns seeded PRNG
        /// Someday, we might want to add more variants on digests.  But for now, Sha256 is the only option.
        /// </summary>
        public static SecureRandom GetSeededDigestRandomGenerator(byte[] seed)
        {
            var prng = new DigestRandomGenerator(new Sha256Digest());

            prng.AddSeedMaterial(seed);
            return(new SecureRandom(prng));
        }
示例#6
0
        public static void WriteRandomBytes(BinaryWriter binaryWriter, int noOfBytes, byte[] entropyBytes, Action <double> setProgressAction = null)
        {
            DigestRandomGenerator digestRandomGenerator = new DigestRandomGenerator(new Sha512Digest());

            digestRandomGenerator.AddSeedMaterial(entropyBytes);

            int blockSize    = 1048576;
            int bytesWritten = 0;

            while (bytesWritten < noOfBytes - blockSize)
            {
                byte[] buffer = new byte[blockSize];
                digestRandomGenerator.NextBytes(buffer);
                binaryWriter.Write(buffer);
                bytesWritten += blockSize;
                if (setProgressAction != null)
                {
                    setProgressAction((double)bytesWritten / (double)noOfBytes * 100.0);
                }
            }

            int remaingBytes = noOfBytes - bytesWritten;

            byte[] buffer2 = new byte[remaingBytes];
            digestRandomGenerator.NextBytes(buffer2);

            binaryWriter.Write(buffer2);
        }
        public void CtrWithHashAlgorithm()
        {
            Span <byte> buffer = stackalloc byte[20];

            using SHA256 sha256 = SHA256.Create();
            using DigestRandomGenerator generator = new DigestRandomGenerator(sha256);
            generator.NextBytes(buffer);
        }
示例#8
0
 public BufferedSecureRandom(byte[] password, int bufferSize = 1024)
 {
     this.bufferSize = bufferSize;
     this.buffer     = new byte[bufferSize];
     this.random     = new DigestRandomGenerator(new Sha1Digest());
     this.random.AddSeedMaterial(password);
     this.random.NextBytes(this.buffer);
 }
 public FastRandomGenerator(SafeRandomGenerator safeRandomGenerator, IDigest digest)
 {
     _safeRandomGenerator = safeRandomGenerator;
     _safeRandomGeneratorIsMineExclusively = false;
     _myPrng     = new DigestRandomGenerator(digest);
     _digestSize = digest.GetDigestSize();
     SeedSize    = _digestSize;
     Reseed();
 }
示例#10
0
 public FastRandomGenerator(List <IEntropyHasher> entropyHashers, IDigest digest)
 {
     _safeRandomGenerator = new SafeRandomGenerator(entropyHashers);
     _safeRandomGeneratorIsMineExclusively = true;
     _myPrng     = new DigestRandomGenerator(digest);
     _digestSize = digest.GetDigestSize();
     SeedSize    = _digestSize;
     Reseed();
 }
示例#11
0
        public static byte[] GetRandomBytes(byte[] entropyBytes, int noOfBytes)
        {
            byte[] randomBytes = new byte[noOfBytes];
            DigestRandomGenerator digestRandomGenerator = new DigestRandomGenerator(new Sha512Digest());

            digestRandomGenerator.AddSeedMaterial(entropyBytes);       //add entropy
            digestRandomGenerator.AddSeedMaterial(DateTime.Now.Ticks); //add additional bytes derived from timestamp
            digestRandomGenerator.NextBytes(randomBytes);
            return(randomBytes);
        }
示例#12
0
文件: Utils.cs 项目: LAToken/lachain
        public static byte[] XorWithHash(G1 g, byte[] data)
        {
            var prng = new DigestRandomGenerator(new Sha3Digest());

            prng.AddSeedMaterial(g.ToBytes());
            var pseudoRandomBytes = new byte[data.Length];

            prng.NextBytes(pseudoRandomBytes);
            return(Xor(pseudoRandomBytes, data));
        }
示例#13
0
        /// <summary>
        /// Creates a deterministic "random number" generator.  SeedUsage ensures that the same
        /// DRBG is not used for different purposes
        /// </summary>
        /// <param name="seed">Seed for the DRNG</param>
        /// <param name="usage">additional seed data in the form of the seed usage</param>
        /// <returns>The deterministic sequence generator</returns>
        private static SecureRandom GetDrbg(byte[] seed, SeedUsage usage)
        {
            DigestRandomGenerator rg     = new DigestRandomGenerator(GetDigest());
            SecureRandom          random = new SecureRandom(rg);

            random.SetSeed(Hash(new byte[1] {
                (byte)usage
            }, seed));
            return(random);
        }
示例#14
0
        /* BouncyCastle DigestRandomGenerator Analysis
         * BouncyCastle DigestRandomGenerator maintains two separate but related internal states, represented by the following:
         *     byte[] seed
         *     long   seedCounter
         *     byte[] state
         *     long   stateCounter
         * The size of seed and state are both equal to the size of the digest.  I am going to refer to the digest size, in bits,
         * as "M".  The counters are obviously 64 bits each.
         *
         * In order to generate repeated output, there would need to be a collision of stateCounter, state, and seed.  We expect a seed
         * collision every 2^(M/2) times that we cycle seed.  We expect a state collision every 2^(M/2) times that we GenerateState,
         * and stateCounter will repeat itself every 2^64 times that we call GenerateState.  This means we can never have a repeated
         * stateCounter&state&seed in less than 2^64 calls to GenerateState, and very likely, it would be much much larger than that.
         *
         * GenerateState is called at least once for every call to NextBytes, and it's called more times, if the number of bytes reqested
         * >= digest size in bytes.  We can easily measure the number of calls to GenerateState, by counting 1+(bytes.Length/digest.Size),
         * and we want to ensure this number is always below 2^64, which is UInt64.MaxValue
         *
         * bytes.Length is an Int32.  We can easily guarantee we'll never repeat an internal state, if we use a UInt64 to tally the
         * number of calls to GenerateState, and require new seed material before UInt64.MaxValue - Int32.MaxValue.  This is a huge number.
         *
         * To put this in perspective, supposing a 128 bit digest, and supposing the user on average requests 8 bytes per call to NextBytes.
         * Then there is guaranteed to be no repeat state before 147 quintillion bytes (147 billion billion).  So let's just tone this
         * down a bit, and choose thresholds that are way more conservative.
         *
         * Completely unrelated to analysis of DigestRandomGenerator, some other prng's (fortuna) recommend new seed material in 2^20
         * iterations, due to limitations they have, which we don't have.  So let's just ensure we end up choosing thresholds that are down
         * on-par with that level, even though completely unnecessary for us, it will feel conservative and safe.
         *
         * Let's use a plain old int to tally the number of calls to GenerateState.  We need to ensure we never overflow this counter, so
         * let's assume all digests are at least 4 bytes, and let's require new seed material every int.MaxValue/2.  This is basically
         * 1 billion calls to NextBytes, so a few GB of random data or so.  Extremely safe and conservative.
         *
         * But let's squish it down even more than that.  FastRandomGenerator performs approx 1,000 times faster than SafeRandomGenerator.  So to
         * maximize the sweet spot between strong security and good performance, let's only stretch the entropy 1,000,000 times at hard
         * maximum, and 64,000 times softly suggested.  Typically, for example with Sha256, this means we'll generate up to 2MB before
         * requesting reseed, and up to 32MB before requiring reseed.
         *
         * Now we're super duper conservative, being zillions of times more conservative than necessary, maximally conservative to the point
         * where we do not take an appreciable performance degradation.
         */

        public FastRandomGenerator()
        {
            _safeRandomGenerator = new SafeRandomGenerator();
            _safeRandomGeneratorIsMineExclusively = true;
            IDigest digest = new Sha512Digest();

            _myPrng     = new DigestRandomGenerator(digest);
            _digestSize = digest.GetDigestSize();
            SeedSize    = _digestSize;
            Reseed();
        }
示例#15
0
        private static DigestRandomGenerator CreatePrng(IDigest digest, bool autoSeed)
        {
            DigestRandomGenerator prng = new DigestRandomGenerator(digest);

            if (autoSeed)
            {
                prng.AddSeedMaterial(NextCounterValue());
                prng.AddSeedMaterial(GetNextBytes(Master, digest.GetDigestSize()));
            }
            return(prng);
        }
示例#16
0
        public void Test_KeccakPrngIsDeterministic()
        {
            var prng = new DigestRandomGenerator(new Sha3Digest());

            prng.AddSeedMaterial(new byte[] { 0xde, 0xad, 0xbe, 0xef });
            var pseudoRandomBytes = new byte[32];

            prng.NextBytes(pseudoRandomBytes);
            Assert.AreEqual(
                "0x4439ed265e4aa7290429a9823b320ccd69dd39128b6fd9a04532d8782f26d70b",
                pseudoRandomBytes.ToHex()
                );
        }
        public void Example_DigestRandomGenerator()
        {
            using DigestRandomGenerator randomGenerator = new DigestRandomGenerator(HashAlgorithmName.SHA256);
            randomGenerator.GenerateSeed(); // seed using current date

            int  randomNnmber = randomGenerator.Next(0, 15);
            uint randomUint   = randomGenerator.Next <uint>();

            randomGenerator.AddSeedMaterial(new byte[] { 45, 78, 12, 0, 0, 45 }); // additional seed material

            byte[] data = new byte[45];
            randomGenerator.NextBytes(data); // get random data
        }
示例#18
0
        public static SecureRandom GetInstance(string algorithm, bool autoSeed)
        {
            string source = Platform.ToUpperInvariant(algorithm);

            if (Platform.EndsWith(source, "PRNG"))
            {
                DigestRandomGenerator generator = CreatePrng(source.Substring(0, source.Length - "PRNG".Length), autoSeed);
                if (generator != null)
                {
                    return(new SecureRandom(generator));
                }
            }
            throw new ArgumentException("Unrecognised PRNG algorithm: " + algorithm, "algorithm");
        }
示例#19
0
    public static SecureRandom GetInstance(string algorithm, bool autoSeed)
    {
        string text = Platform.ToUpperInvariant(algorithm);

        if (Platform.EndsWith(text, "PRNG"))
        {
            string digestName = text.Substring(0, text.Length - "PRNG".Length);
            DigestRandomGenerator digestRandomGenerator = CreatePrng(digestName, autoSeed);
            if (digestRandomGenerator != null)
            {
                return(new SecureRandom(digestRandomGenerator));
            }
        }
        throw new ArgumentException("Unrecognised PRNG algorithm: " + algorithm, "algorithm");
    }
示例#20
0
        /// <summary>
        /// Create an instance based on the given algorithm, with optional auto-seeding
        /// </summary>
        /// <param name="algorithm">e.g. "SHA256PRNG"</param>
        /// <param name="autoSeed">If true, the instance will be auto-seeded.</param>
        public static SecureRandom GetInstance(string algorithm, bool autoSeed)
        {
            string upper = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm);

            if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(upper, "PRNG"))
            {
                string digestName          = upper.Substring(0, upper.Length - "PRNG".Length);
                DigestRandomGenerator prng = CreatePrng(digestName, autoSeed);
                if (prng != null)
                {
                    return(new SecureRandom(prng));
                }
            }

            throw new ArgumentException("Unrecognised PRNG algorithm: " + algorithm, "algorithm");
        }
示例#21
0
        public static SecureRandom GetInstance(string algorithm, bool autoSeed)
        {
            //IL_004f: Unknown result type (might be due to invalid IL or missing references)
            string text = Platform.ToUpperInvariant(algorithm);

            if (Platform.EndsWith(text, "PRNG"))
            {
                string digestName = text.Substring(0, text.get_Length() - "PRNG".get_Length());
                DigestRandomGenerator digestRandomGenerator = CreatePrng(digestName, autoSeed);
                if (digestRandomGenerator != null)
                {
                    return(new SecureRandom(digestRandomGenerator));
                }
            }
            throw new ArgumentException("Unrecognised PRNG algorithm: " + algorithm, "algorithm");
        }
 internal FastRandomGenerator(
     SafeRandomGenerator safeRng,
     bool ownsSafeRng,
     IDigest digest)
 {
     if (digest == null)
     {
         throw new ArgumentNullException(nameof(digest));
     }
     _safeRandomGenerator     = safeRng ?? throw new ArgumentNullException(nameof(safeRng));
     _ownsSafeRandomGenerator = ownsSafeRng;
     _prng       = new DigestRandomGenerator(digest);
     _digestSize = digest.GetDigestSize();
     SeedSize    = _digestSize;
     Reseed();
 }
示例#23
0
        private static DigestRandomGenerator CreatePrng(string digestName, bool autoSeed)
        {
            IDigest digest = DigestUtilities.GetDigest(digestName);

            if (digest == null)
            {
                return(null);
            }
            DigestRandomGenerator prng = new DigestRandomGenerator(digest);

            if (autoSeed)
            {
                prng.AddSeedMaterial(NextCounterValue());
                prng.AddSeedMaterial(GetSeed(digest.GetDigestSize()));
            }
            return(prng);
        }
示例#24
0
 public DTLSContext(bool client, Version version, HandshakeInfo handshakeInfo)
 {
     IsServer = !client;
     if (version == DTLSRecord.Version1_2)
     {
         ClientVersion = ProtocolVersion.DTLSv12;
         ServerVersion = ProtocolVersion.DTLSv12;
     }
     else
     {
         ClientVersion = ProtocolVersion.DTLSv10;
         ServerVersion = ProtocolVersion.DTLSv10;
     }
     SecurityParameters   = new DTLSSecurityParameters(version, handshakeInfo);
     NonceRandomGenerator = new DigestRandomGenerator(TlsUtilities.CreateHash(HashAlgorithm.sha256));
     NonceRandomGenerator.AddSeedMaterial(Times.NanoTime());
 }
示例#25
0
        private static DigestRandomGenerator CreatePrng(string digestName, bool autoSeed)
        {
            IDigest digest = FipsShs.CreateDigest(FipsShs.Sha256);

            if (digest == null)
            {
                return(null);
            }
            DigestRandomGenerator prng = new DigestRandomGenerator(digest);

            if (autoSeed)
            {
                prng.AddSeedMaterial(NextCounterValue());
                prng.AddSeedMaterial(GetNextBytes(Master, digest.GetDigestSize()));
            }
            return(prng);
        }
示例#26
0
        private static DigestRandomGenerator CreatePrng(string digestName, bool autoSeed)
        {
            IDigest digest = DigestUtilities.GetDigest(digestName);

            if (digest == null)
            {
                return(null);
            }
            DigestRandomGenerator digestRandomGenerator = new DigestRandomGenerator(digest);

            if (autoSeed)
            {
                digestRandomGenerator.AddSeedMaterial(NextCounterValue());
                digestRandomGenerator.AddSeedMaterial(GetNextBytes(Master, digest.GetDigestSize()));
            }
            return(digestRandomGenerator);
        }
示例#27
0
        private void doCountTest(IDigest digest, byte[] seed, byte[] expectedXors)
        {
            DigestRandomGenerator rGen = new DigestRandomGenerator(digest);

            byte[] output   = new byte[digest.GetDigestSize()];
            int[]  averages = new int[digest.GetDigestSize()];
            byte[] ands     = new byte[digest.GetDigestSize()];
            byte[] xors     = new byte[digest.GetDigestSize()];
            byte[] ors      = new byte[digest.GetDigestSize()];

            rGen.AddSeedMaterial(seed);

            for (int i = 0; i != 1000000; i++)
            {
                rGen.NextBytes(output);
                for (int j = 0; j != output.Length; j++)
                {
                    averages[j] += output[j] & 0xff;
                    ands[j]     &= output[j];
                    xors[j]     ^= output[j];
                    ors[j]      |= output[j];
                }
            }

            for (int i = 0; i != output.Length; i++)
            {
                if ((averages[i] / 1000000) != 127)
                {
                    Fail("average test failed for " + digest.AlgorithmName);
                }
                if (ands[i] != 0)
                {
                    Fail("and test failed for " + digest.AlgorithmName);
                }
                if ((ors[i] & 0xff) != 0xff)
                {
                    Fail("or test failed for " + digest.AlgorithmName);
                }
                if (xors[i] != expectedXors[i])
                {
                    Fail("xor test failed for " + digest.AlgorithmName);
                }
            }
        }
        private static IRandomGenerator CreateNonceRandom(SecureRandom secureRandom, int connectionEnd)
        {
            byte[] additionalSeedMaterial = new byte[16];
            Pack.UInt64_To_BE((ulong)NextCounterValue(), additionalSeedMaterial, 0);
            Pack.UInt64_To_BE((ulong)Times.NanoTime(), additionalSeedMaterial, 8);
            additionalSeedMaterial[0] &= 0x7F;
            additionalSeedMaterial[0] |= (byte)(connectionEnd << 7);

            IDigest digest = TlsUtilities.CreateHash(HashAlgorithm.sha256);

            byte[] seed = new byte[digest.GetDigestSize()];
            secureRandom.NextBytes(seed);

            IRandomGenerator nonceRandom = new DigestRandomGenerator(digest);

            nonceRandom.AddSeedMaterial(additionalSeedMaterial);
            nonceRandom.AddSeedMaterial(seed);
            return(nonceRandom);
        }
示例#29
0
        /// <summary>
        /// Creates a cryptographically strong string with the given digest
        /// </summary>
        /// <typeparam name="TDigest">Hash type</typeparam>
        /// <param name="stringType">Filter to apply to string</param>
        /// <returns>A string with only the characters defined by stringType</returns>
        private static string CreateCryptographicallyStrongString <TDigest>(
            CryptoStringTypeEnum stringType)
            where TDigest : IDigest, new()
        {
            var randomBytes = BitConverter.GetBytes(
                new SecureRandom().NextInt());

            var digest = new TDigest();

            digest.BlockUpdate(
                randomBytes,
                0,
                randomBytes.Length);
            var randomDigest = new DigestRandomGenerator(digest);

            var cryptoData = new byte[digest.GetDigestSize()];

            randomDigest.NextBytes(cryptoData);

            var result = Convert.ToBase64String(cryptoData);


            switch (stringType)
            {
            case CryptoStringTypeEnum.Base64AlphaNumeric:
                return(result
                       .Replace('/', '_')
                       .Replace('+', '-'));

            case CryptoStringTypeEnum.LowercaseAlphaNumeric:
                return(result
                       .Replace('/', 'a')
                       .Replace('+', 'b')
                       .ToLower());

            case CryptoStringTypeEnum.Base64:
            default:
                return(result);
            }
        }
示例#30
0
        private void HandleAuthorizationRequest(AuthorizationRequestPacket packet)
        {
            if (Authorized)
            {
                return;
            }

            SendPacket(new AuthorizationResponsePacket {
                AuthorizationStatus = AuthorizationStatus
            });

            if (AuthorizationStatus.HasFlag(AuthorizationStatus.EncryprionEnabled))
            {
                var publicKey = Module.Security.RSAKeyPair.PublicKeyToByteArray();

                VerificationToken = new byte[4];
                var drg = new DigestRandomGenerator(new Sha512Digest());
                drg.NextBytes(VerificationToken);

                SendPacket(new EncryptionRequestPacket {
                    PublicKey = publicKey, VerificationToken = VerificationToken
                });
            }
        }
 private static DigestRandomGenerator CreatePrng(string digestName, bool autoSeed)
 {
     IDigest digest = DigestUtilities.GetDigest(digestName);
     if (digest == null)
         return null;
     DigestRandomGenerator prng = new DigestRandomGenerator(digest);
     if (autoSeed)
     {
         prng.AddSeedMaterial(NextCounterValue());
         prng.AddSeedMaterial(GetSeed(digest.GetDigestSize()));
     }
     return prng;
 }