Пример #1
0
 public override void SetSeed(byte[] seed)
 {
     lock (this)
     {
         if (mRandomSource != null)
         {
             mRandomSource.SetSeed(seed);
         }
     }
 }
Пример #2
0
        public void Test1000()
        {
            byte[]       testData = new byte[10000];
            SecureRandom rand     = new SecureRandom();

            rand.SetSeed(0);

            for (int i = 0; i != 10; i++)
            {
                CmsCompressedDataStreamGenerator gen = new CmsCompressedDataStreamGenerator();
                MemoryStream bOut = new MemoryStream();

                Stream cOut = gen.Open(bOut, CmsCompressedDataStreamGenerator.ZLib);

                rand.NextBytes(testData);

                cOut.Write(testData, 0, testData.Length);

                cOut.Close();

                CmsCompressedDataParser ed = new CmsCompressedDataParser(bOut.ToArray());

                Assert.IsTrue(Arrays.AreEqual(testData, CmsTestUtil.StreamToByteArray(ed.GetContent().ContentStream)));
            }
        }
Пример #3
0
        public static void GenerateKey(
            out byte[] privateKey, out byte[] publicKey)
        {
            var rnd = new SecureRandom();

            rnd.SetSeed(DateTime.UtcNow.Ticks);

            var curve = SecNamedCurves.GetByName(CurveName);
            var n     = curve.N;

            BigInteger d;

            do
            {
                d = new BigInteger(n.BitLength, rnd).SetBit(n.BitLength - 1);
            } while (d.CompareTo(n) >= 0);
            privateKey = d.ToByteArrayUnsigned();

            var pubPoint = curve.G.Multiply(d).Normalize();

            publicKey = ToBytes(new ECPoint
            {
                X = pubPoint.XCoord.GetEncoded(),
                Y = pubPoint.YCoord.GetEncoded(),
            });
        }
        public void TestVmpcPrng()
        {
            var random = new SecureRandom(new VmpcRandomGenerator());
            random.SetSeed(SecureRandom.GetSeed(32));

            CheckSecureRandom(random);
        }
Пример #5
0
        /// <summary>
        /// Generates a random password with a high entropy.
        /// </summary>
        /// <returns>Random ASCII password.</returns>
        public static string GenerateRandomPassword()
        {
            var    passArray = new char[30];
            string password;

            var csprng = new SecureRandom(new DigestRandomGenerator(new Sha256Digest()));

            csprng.SetSeed(DateTime.Now.Ticks); // TODO: is this a good seed value?

            while (true)
            {
                for (var i = 0; i < 30; ++i)
                {
                    // ASCII printable characters are >= SPACE (0x20) and < DEL (0x7e).
                    passArray[i] = (char)csprng.Next(0x20, 0x7f);
                }

                password = new string(passArray);
                //passArray = Enumerable.Repeat('0', passArray.Length).ToArray(); // zeroization

                if (PasswordAdvisor.IsPasswordStrong(password, out var _, false))
                {
                    break;
                }
            }

            return(password);
        }
Пример #6
0
        public static void StartGenerateKeypair(byte[] seed, GenCompleteEventHandler evt)
        {
            Thread genThread = new Thread(new ParameterizedThreadStart((o) =>
            {
                //create a random number generator using SHA512 algorithm
                SecureRandom rnd = SecureRandom.GetInstance(RANDOM_ALGO);
                rnd.SetSeed(seed);

                X9ECParameters curve      = TeleTrusTNamedCurves.GetByName(ECDSA_CURVE);
                ECDomainParameters domain = new ECDomainParameters(curve.Curve, curve.G, curve.N);

                //create the parameters for initializing the key pair generator using the brainpoolp384t1 curve
                ECKeyGenerationParameters parms = new ECKeyGenerationParameters(domain, rnd);

                //create and initialize the key pair generator
                ECKeyPairGenerator gen = new ECKeyPairGenerator("ECDSA");
                gen.Init(parms);

                //generate the key pair
                AsymmetricCipherKeyPair kp = gen.GenerateKeyPair();

                //trigger the event
                Xamarin.Forms.Device.BeginInvokeOnMainThread(() =>
                {
                    if (evt != null)
                    {
                        evt(kp);
                    }
                });
            }));

            genThread.Start();
        }
Пример #7
0
        /*
         * Creates and seeds a new SecureRandom to be used for keypair creation
         */
        static SecureRandom CreateNewSecureRandom(ApplicationContext context, Node args)
        {
            // Used to to hold seed for random number generator.
            List <byte> seed = new List <byte> ();

            // First we retrieve the seed provided by caller through the [seed] argument, defaulting to "foobar" if no user seed is provided.
            seed.AddRange(Encoding.UTF8.GetBytes(args.GetExChildValue <string> ("seed", context, "foobar") ?? "foobar"));

            // Then we retrieve a cryptographically secure random number of 128 bytes.
            seed.AddRange(context.RaiseEvent("p5.crypto.create-random", new Node("", null, new Node [] { new Node("resolution", 128), new Node("raw", true) })).Get <byte []> (context));

            // Then retrieving "seed generator" from BouncyCastle.
            seed.AddRange(new ThreadedSeedGenerator().GenerateSeed(128, false));

            // Then we retrieve the server password salt.
            seed.AddRange(Encoding.UTF8.GetBytes(context.RaiseEvent(".p5.auth.get-server-salt").Get <string> (context)));

            // Then we retrieve the ticks of server.
            seed.AddRange(Encoding.UTF8.GetBytes(DateTime.Now.Ticks.ToString()));

            // Then appending a randomly created Guid.
            seed.AddRange(Encoding.UTF8.GetBytes(Guid.NewGuid().ToString()));

            // Then we change the "user seed" to make sure consecutive invocations does not in any ways use the same original seed.
            args.FindOrInsert("seed").Value = context.RaiseEvent("p5.crypto.hash.create-sha512", new Node("", seed)).Get <string> (context);

            // At this point, we are fairly certain that we have a pretty random and cryptographically secure seed.
            // Provided that SecureRandom from BouncyCastle is implemented correctly, we should now have a VERY, VERY, VERY unique,
            // and cryptographically secure Random Number seed!
            SecureRandom retVal = new SecureRandom();

            retVal.SetSeed(seed.ToArray());

            return(retVal);
        }
Пример #8
0
        public void GenRSAKeyPair(string name)
        {
            var generator    = new RsaKeyPairGenerator();
            var seed         = Encoding.UTF8.GetBytes(name);
            var secureRandom = new SecureRandom();

            secureRandom.SetSeed(seed);
            generator.Init(new KeyGenerationParameters(secureRandom, 2048));
            var pair = generator.GenerateKeyPair();


            var       twPrivate = new StringWriter();
            PemWriter pwPrivate = new PemWriter(twPrivate);

            pwPrivate.WriteObject(pair.Private);
            pwPrivate.Writer.Flush();
            var privateKey = twPrivate.ToString().Replace("-----BEGIN RSA PRIVATE KEY-----", "").Replace("-----END RSA PRIVATE KEY-----", "").Trim();

            Console.WriteLine(privateKey);

            var       twPublic = new StringWriter();
            PemWriter pwPublic = new PemWriter(twPublic);

            pwPublic.WriteObject(pair.Public);
            pwPublic.Writer.Flush();
            var publicKey = twPublic.ToString().Replace("-----BEGIN PUBLIC KEY-----", "").Replace("-----END PUBLIC KEY-----", "").Trim();

            Console.WriteLine(publicKey);
        }
Пример #9
0
        public static string[] GenerateKeys(byte[] seed)
        {
            ECKeyPairGenerator gen = new ECKeyPairGenerator();

            var secureRandom = new SecureRandom();

            secureRandom.SetSeed(seed);
            var keyGenParam = new ECKeyGenerationParameters(domain, secureRandom);

            gen.Init(keyGenParam);

            AsymmetricCipherKeyPair keyPair = gen.GenerateKeyPair();

            ECPrivateKeyParameters privateParams = (ECPrivateKeyParameters)keyPair.Private;
            ECPublicKeyParameters  publicParams  = (ECPublicKeyParameters)keyPair.Public;

            BigInteger privateKey = privateParams.D;
            BigInteger publicKey  = new BigInteger(publicParams.Q.GetEncoded());

            BigInteger publicKeyCompressed = new BigInteger(publicParams.Q.GetEncoded(true));

            string[] walletKeyPair = new string[2];

            walletKeyPair[0] = privateKey.ToString(16);
            walletKeyPair[1] = publicKey.ToString(16);

            return(walletKeyPair);
        }
Пример #10
0
        public static int PseudoRandomNumber(int lower = 1000, int upper = 9999)
        {
            SecureRandom random = new SecureRandom();

            random.SetSeed(GenerateRandomBytes());
            int number = random.Next(lower, upper);

            for (int i = 0; i < random.Next(lower, upper); i++)
            {
                if (i % 100 == 0)
                {
                    random.SetSeed(GenerateRandomBytes());
                }
                number = random.Next(lower, upper);
            }
            return(number);
        }
Пример #11
0
        public void TestVmpcPrng()
        {
            SecureRandom random = new SecureRandom(new VmpcRandomGenerator());

            random.SetSeed(random.GenerateSeed(32));

            CheckSecureRandom(random);
        }
Пример #12
0
        public void TestThreadedSeed()
        {
            SecureRandom random = SecureRandom.GetInstance("SHA1PRNG", false);

            random.SetSeed(new ThreadedSeedGenerator().GenerateSeed(20, false));

            CheckSecureRandom(random);
        }
Пример #13
0
        /// <summary>
        ///     Class implementing Belare and Neven Multi-signature
        ///     See "Multi-Signatures in the Plain Public-Key Model and a General Forking Lemma"
        ///     - <see href="https://cseweb.ucsd.edu/~mihir/papers/multisignatures-ccs.pdf" />
        ///     - Port <see href="https://github.com/ElrondNetwork/elrond-node-prototype/blob/master/elrond-core/" />
        /// </summary>
        /// <param name="secp256k1"></param>
        public MultiSignature(ISecp256k1 secp256k1)
        {
            _secp256k1    = secp256k1;
            _secureRandom = new SecureRandom();
            var seed = _secureRandom.GenerateSeed(32);

            _secureRandom.SetSeed(seed);
        }
        public void TestSha256Prng()
        {
            SecureRandom random = SecureRandom.GetInstance("SHA256PRNG");

            random.SetSeed(SecureRandom.GetSeed(32));

            checkSecureRandom(random);
        }
        public void TestSha1Prng()
        {
            SecureRandom random = SecureRandom.GetInstance("SHA1PRNG");

            random.SetSeed(SecureRandom.GetSeed(20));

            checkSecureRandom(random);
        }
Пример #16
0
        public static SecureRandom GetSecureRandom()
        {
            SecureRandom random = new SecureRandom();
            int          rnd    = CryptoHelper.PseudoRandomNumber();

            random.SetSeed(random.GenerateSeed(rnd));
            return(random);
        }
        /// <summary>
        /// Builds a SecureRandom with seed filled in.
        /// </summary>
        /// <returns></returns>
        public static SecureRandom GetSecureRandom()
        {
            SecureRandom secureRandom = SecureRandom.GetInstance("SHA1PRNG", false);

            byte[] seed = new byte[1024];
            secureRandom.NextBytes(seed);
            secureRandom.SetSeed(seed);
            return(secureRandom);
        }
Пример #18
0
        /// <summary>
        /// Implementation of slot.
        /// </summary>
        /// <param name="signaler">Signaler invoking slot.</param>
        /// <param name="input">Arguments to slot.</param>
        public void Signal(ISignaler signaler, Node input)
        {
            // Retrieving arguments.
            var seedStr = input.GetEx <string>() ?? throw new ArgumentException("No value provided to [crypto.seed]");
            var seed    = Encoding.UTF8.GetBytes(seedStr);
            var rnd     = new SecureRandom();

            rnd.SetSeed(seed);
        }
Пример #19
0
        private void RandomTests()
        {
            SecureRandom srng = new SecureRandom();

            srng.SetSeed(DateTimeUtilities.CurrentUnixMs());
            RandomTests(srng, null);
            RandomTests(srng, new BasicGcmMultiplier());
            RandomTests(srng, new Tables8kGcmMultiplier());
            RandomTests(srng, new Tables64kGcmMultiplier());
        }
Пример #20
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);
        }
Пример #21
0
        private void RandomTests()
        {
            SecureRandom srng = new SecureRandom();

            srng.SetSeed(DateTimeUtilities.CurrentUnixMs());
            for (int i = 0; i < 10; ++i)
            {
                RandomTest(srng);
            }
        }
Пример #22
0
        public static string InitKey(string seed)
        {
            SecureRandom rnd = new SecureRandom();

            if (seed != null)
            {
                rnd.SetSeed(Base64.Decode(seed));
            }
            return(InitKey(rnd));
        }
Пример #23
0
        public static void GenerateSymKey(int keyLength)
        {
            var sec = new SecureRandom();

            sec.SetSeed(DateTime.Now.ToBinary());
            var keyParam     = new KeyGenerationParameters(sec, keyLength);
            var keyGenerator = new CipherKeyGenerator();

            keyGenerator.Init(keyParam);
            symKey = keyGenerator.GenerateKey();
        }
Пример #24
0
        private void RandomTests()
        {
            SecureRandom random = new SecureRandom();

            random.SetSeed(DateTimeUtilities.CurrentUnixMs());

            for (int i = 0; i < 100; ++i)
            {
                RandomTest(random);
            }
        }
Пример #25
0
        /// <summary>
        /// Implementation of <em>Needle in a Haystack</em> steganography. Encrypted RSA key in its entirety is hidden in a 100,000 times bigger binary file.
        /// </summary>
        /// <param name="privateKeyPath">Path to users private key.</param>
        /// <param name="needle">Users encrypted private key.</param>
        /// <param name="salt">Salt used to create password digest.</param>
        /// <param name="passwordDigest">Users password digest.</param>
        private void HideMyNeedle(string privateKeyPath, byte[] needle, byte[] salt, byte[] passwordDigest)
        {
            var rootDir = new FileInfo(privateKeyPath).Directory.Root.FullName;
            var path    = privateKeyPath.Substring(0, privateKeyPath.LastIndexOf('\\')) + "\\key.bin";

            // TODO: add MAC/HMAC and secure deletion of original RSA key
            var csprng = new SecureRandom(new DigestRandomGenerator(new Sha256Digest()));

            csprng.SetSeed(DateTime.Now.Ticks); // TODO: is this a good seed value?

            var haystackSize = (needle.Length + csprng.Next(1_024, 4_096)) * 100_000;
            int startLocation;

            if (new DriveInfo(rootDir).AvailableFreeSpace > haystackSize)
            {
                var haystack = new byte[haystackSize];
                new RNGCryptoServiceProvider().GetBytes(haystack);

                startLocation = csprng.Next(4 + 4 + 16 + 32, haystackSize - needle.Length);     // 4 for startLocation (int) + 4 for haystackSize (int) + 16 for salt + 32 for passwordDigest

                var startLocationBytes = BitConverter.GetBytes(startLocation);

                //if (BitConverter.IsLittleEndian)
                //    Array.Reverse(startLocationBytes);

                Buffer.BlockCopy(startLocationBytes, 0, haystack, 0, 4);                        // copy startLocation

                var needleSize = BitConverter.GetBytes(needle.Length);

                //if (BitConverter.IsLittleEndian)
                //    Array.Reverse(haystackSizeBytes);

                Buffer.BlockCopy(needleSize, 0, haystack, 4, 4);                                // copy needleSize

                Buffer.BlockCopy(salt, 0, haystack, 8, 16);                                     // copy salt

                Buffer.BlockCopy(passwordDigest, 0, haystack, 24, 32);                          // copy passwordDigest

                Buffer.BlockCopy(needle, 0, haystack, startLocation, needle.Length);            // copy the needle (encrypted key)

                using var stream  = new FileStream(path, FileMode.Create);
                using var writter = new BinaryWriter(stream);
                writter.Write(haystack);

                //// data scrambling
                //new RNGCryptoServiceProvider().GetBytes(salt);
                //new RNGCryptoServiceProvider().GetBytes(haystack);
                //new RNGCryptoServiceProvider().GetBytes(passwordDigest);
            }
            else
            {
                throw new Exception("Insufficient storage available.");
            }
        }
Пример #26
0
        public void TestSha1PrngBackward()
        {
            byte[] seed = Encoding.ASCII.GetBytes("backward compatible");

            SecureRandom sx = new SecureRandom(seed);
            SecureRandom sy = SecureRandom.GetInstance("SHA1PRNG", false); sy.SetSeed(seed);

            byte[] bx = new byte[128]; sx.NextBytes(bx);
            byte[] by = new byte[128]; sy.NextBytes(by);

            Assert.IsTrue(Arrays.AreEqual(bx, by));
        }
        private void RandMult(string label, X9ECParameters spec)
        {
            ECCurve    C = spec.Curve;
            ECPoint    G = (ECPoint)spec.G;
            BigInteger n = spec.N;

            SecureRandom random = new SecureRandom();

            random.SetSeed(DateTimeUtilities.CurrentUnixMs());

            Console.WriteLine(label);

            int[] coords = ECCurve.GetAllCoordinateSystems();
            for (int i = 0; i < coords.Length; ++i)
            {
                int coord = coords[i];
                if (C.SupportsCoordinateSystem(coord))
                {
                    ECCurve c = C;
                    ECPoint g = G;

                    bool defaultCoord = (c.CoordinateSystem == coord);
                    if (!defaultCoord)
                    {
                        c = C.Configure().SetCoordinateSystem(coord).Create();
                        g = c.ImportPoint(G);
                    }

                    double        avgRate   = RandMult(random, g, n);
                    string        coordName = COORD_NAMES[coord];
                    StringBuilder sb        = new StringBuilder();
                    sb.Append("   ");
                    sb.Append(defaultCoord ? '*' : ' ');
                    sb.Append(coordName);
                    for (int j = sb.Length; j < 30; ++j)
                    {
                        sb.Append(' ');
                    }
                    sb.Append(": ");
                    sb.Append(avgRate);
                    sb.Append(" mults/sec");
                    for (int j = sb.Length; j < 64; ++j)
                    {
                        sb.Append(' ');
                    }
                    sb.Append('(');
                    sb.Append(1000.0 / avgRate);
                    sb.Append(" millis/mult)");
                    Console.WriteLine(sb.ToString());
                }
            }
        }
Пример #28
0
        private AsymmetricCipherKeyPair GenerateRsaKeys(byte[] seed)
        {
            SecureRandom sr = new SecureRandom();

            sr.SetSeed(seed);

            var kpg = new RsaKeyPairGenerator();

            kpg.Init(new RsaKeyGenerationParameters(BigInteger.ValueOf(0x13), sr, 4096, 8));;
            AsymmetricCipherKeyPair keys = kpg.GenerateKeyPair();

            return(keys);
        }
        public static AsymmetricCipherKeyPair GenerateRandomKeys(string seed = null, int keySize = 256)
        {
            var gen          = new ECKeyPairGenerator();
            var secureRandom = new SecureRandom();

            if (seed != null)
            {
                var seedBytes = Encoding.ASCII.GetBytes(seed);
                secureRandom.SetSeed(seedBytes);
            }
            var keyGenParams = new KeyGenerationParameters(secureRandom, keySize);

            gen.Init(keyGenParams);
            return(gen.GenerateKeyPair());
        }
Пример #30
0
        private static SecureString GenerateNewMachineKey(int keySize)
        {
            var random = new SecureRandom();

            random.SetSeed(random.GenerateSeed(128));

            var machineKeyString = "";

            for (var x = 0; x < keySize; x++)
            {
                machineKeyString += (char)random.Next(33, 126);
            }

            return(machineKeyString.ConvertToSecureString());
        }
Пример #31
0
        public override void PerformTest()
        {
            SecureRandom rand = new SecureRandom(new byte[20]);

            rand.SetSeed(DateTime.Now.Ticks);

            doTestPadding(new Pkcs7Padding(), rand,
                          Hex.Decode("ffffff0505050505"),
                          Hex.Decode("0000000004040404"));

            Pkcs7Padding padder = new Pkcs7Padding();

            try
            {
                padder.PadCount(new byte[8]);

                Fail("invalid padding not detected");
            }
            catch (InvalidCipherTextException e)
            {
                if (!"pad block corrupted".Equals(e.Message))
                {
                    Fail("wrong exception for corrupt padding: " + e);
                }
            }

            doTestPadding(new ISO10126d2Padding(), rand,
                          null,
                          null);

            doTestPadding(new X923Padding(), rand,
                          null,
                          null);

            doTestPadding(new TbcPadding(), rand,
                          Hex.Decode("ffffff0000000000"),
                          Hex.Decode("00000000ffffffff"));

            doTestPadding(new ZeroBytePadding(), rand,
                          Hex.Decode("ffffff0000000000"),
                          null);

            doTestPadding(new ISO7816d4Padding(), rand,
                          Hex.Decode("ffffff8000000000"),
                          Hex.Decode("0000000080000000"));
        }