/// <exception cref="System.Exception"/>
            public KeyProvider.KeyVersion Run()
            {
                KeyProvider.Options          opt = TestKeyAuthorizationKeyProvider.NewOptions(conf);
                IDictionary <string, string> m   = new Dictionary <string, string>();

                m["key.acl.name"] = "testKey";
                opt.SetAttributes(m);
                try
                {
                    KeyProvider.KeyVersion kv = kpExt.CreateKey("foo", SecureRandom.GetSeed(16), opt);
                    kpExt.RollNewVersion(kv.GetName());
                    kpExt.RollNewVersion(kv.GetName(), SecureRandom.GetSeed(16));
                    kpExt.DeleteKey(kv.GetName());
                }
                catch (IOException)
                {
                    NUnit.Framework.Assert.Fail("User should be Authorized !!");
                }
                KeyProvider.KeyVersion retkv = null;
                try
                {
                    retkv = kpExt.CreateKey("bar", SecureRandom.GetSeed(16), opt);
                    kpExt.GenerateEncryptedKey(retkv.GetName());
                    NUnit.Framework.Assert.Fail("User should NOT be Authorized to generate EEK !!");
                }
                catch (IOException)
                {
                }
                NUnit.Framework.Assert.IsNotNull(retkv);
                return(retkv);
            }
Esempio n. 2
0
        private static double MeasureChiSquared(SecureRandom random, int rounds)
        {
            byte[] opts   = SecureRandom.GetSeed(2);
            int[]  counts = new int[256];

            byte[] bs = new byte[256];
            for (int i = 0; i < rounds; ++i)
            {
                random.NextBytes(bs);

                for (int b = 0; b < 256; ++b)
                {
                    ++counts[bs[b]];
                }
            }

            byte mask = opts[0];

            for (int i = 0; i < rounds; ++i)
            {
                random.NextBytes(bs);

                for (int b = 0; b < 256; ++b)
                {
                    ++counts[bs[b] ^ mask];
                }

                ++mask;
            }

            byte shift = opts[1];

            for (int i = 0; i < rounds; ++i)
            {
                random.NextBytes(bs);

                for (int b = 0; b < 256; ++b)
                {
                    ++counts[(byte)(bs[b] + shift)];
                }

                ++shift;
            }

            int total = 3 * rounds;

            double chi2 = 0;

            for (int k = 0; k < counts.Length; ++k)
            {
                double diff  = ((double)counts[k]) - total;
                double diff2 = diff * diff;

                chi2 += diff2;
            }

            chi2 /= total;

            return(chi2);
        }
Esempio n. 3
0
        public void TestVmpcPrng()
        {
            SecureRandom random = new SecureRandom(new VmpcRandomGenerator());

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

            CheckSecureRandom(random);
        }
        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);
        }
        /// <summary>
        /// Encrypts and encodes the private key.
        /// </summary>
        /// <param name="key">The private key.</param>
        /// <param name="passPhrase">The pass phrase to encrypt the private key.</param>
        /// <returns>The encrypted private key.</returns>
        public static string ToEncryptedPrivateKeyString(AsymmetricKeyParameter key, string passPhrase)
        {
            var salt         = new byte[16];
            var secureRandom = SecureRandom.GetInstance("SHA256PRNG");

            secureRandom.SetSeed(SecureRandom.GetSeed(16));               //See Bug #135
            secureRandom.NextBytes(salt);

            return(Convert.ToBase64String(PrivateKeyFactory.EncryptKey(keyEncryptionAlgorithm, passPhrase.ToCharArray(), salt, 10, key)));
        }
 public static void Setup()
 {
     conf    = new Configuration();
     kp      = new UserProvider.Factory().CreateProvider(new URI("user:///"), conf);
     kpExt   = KeyProviderCryptoExtension.CreateKeyProviderCryptoExtension(kp);
     options = new KeyProvider.Options(conf);
     options.SetCipher(Cipher);
     options.SetBitLength(128);
     encryptionKey = kp.CreateKey(EncryptionKeyName, SecureRandom.GetSeed(16), options
                                  );
 }
 /// <exception cref="System.Exception"/>
 public Void Run()
 {
     try
     {
         kpExt.CreateKey("foo", SecureRandom.GetSeed(16), TestKeyAuthorizationKeyProvider.
                         NewOptions(conf));
         NUnit.Framework.Assert.Fail("User should NOT be Authorized !!");
     }
     catch (IOException)
     {
     }
     // Ignore
     return(null);
 }
            /// <exception cref="System.Exception"/>
            public Void Run()
            {
                KeyProvider.Options          opt = TestKeyAuthorizationKeyProvider.NewOptions(conf);
                IDictionary <string, string> m   = new Dictionary <string, string>();

                m["key.acl.name"] = "testKey";
                opt.SetAttributes(m);
                KeyProvider.KeyVersion kv = kpExt.CreateKey("foo", SecureRandom.GetSeed(16), opt);
                kpExt.RollNewVersion(kv.GetName());
                kpExt.RollNewVersion(kv.GetName(), SecureRandom.GetSeed(16));
                KeyProviderCryptoExtension.EncryptedKeyVersion ekv = kpExt.GenerateEncryptedKey(kv
                                                                                                .GetName());
                ekv = KeyProviderCryptoExtension.EncryptedKeyVersion.CreateForDecryption(ekv.GetEncryptionKeyName
                                                                                             () + "x", ekv.GetEncryptionKeyVersionName(), ekv.GetEncryptedKeyIv(), ekv.GetEncryptedKeyVersion
                                                                                             ().GetMaterial());
                kpExt.DecryptEncryptedKey(ekv);
                return(null);
            }
            /// <exception cref="System.Exception"/>
            public Void Run()
            {
                KeyProvider.Options          opt = TestKeyAuthorizationKeyProvider.NewOptions(conf);
                IDictionary <string, string> m   = new Dictionary <string, string>();

                m["key.acl.name"] = "testKey";
                opt.SetAttributes(m);
                try
                {
                    KeyProvider.KeyVersion kv = kpExt.CreateKey("foo", SecureRandom.GetSeed(16), opt);
                    kpExt.RollNewVersion(kv.GetName());
                    kpExt.RollNewVersion(kv.GetName(), SecureRandom.GetSeed(16));
                    KeyProviderCryptoExtension.EncryptedKeyVersion ekv = kpExt.GenerateEncryptedKey(kv
                                                                                                    .GetName());
                    kpExt.DecryptEncryptedKey(ekv);
                    kpExt.DeleteKey(kv.GetName());
                }
                catch (IOException)
                {
                    NUnit.Framework.Assert.Fail("User should be Allowed to do everything !!");
                }
                return(null);
            }
        /**
         * Method init
         *
         * @param forWrapping
         * @param param
         */
        public void Init(
            bool forWrapping,
            ICipherParameters parameters)
        {
            this.forWrapping = forWrapping;
            this.engine      = new CbcBlockCipher(new DesEdeEngine());

            if (parameters is KeyParameter)
            {
                this.param = (KeyParameter)parameters;
                if (this.forWrapping)
                {
                    // Hm, we have no IV but we want to wrap ?!?
                    // well, then we have to create our own IV.
                    this.iv = SecureRandom.GetSeed(8);

                    this.paramPlusIV = new ParametersWithIV(this.param, this.iv);
                }
            }
            else if (parameters is ParametersWithIV)
            {
                if (!forWrapping)
                {
                    throw new ArgumentException("You should not supply an IV for unwrapping");
                }

                this.paramPlusIV = (ParametersWithIV)parameters;
                this.iv          = this.paramPlusIV.GetIV();
                this.param       = (KeyParameter)this.paramPlusIV.Parameters;

                if (this.iv.Length != 8)
                {
                    throw new ArgumentException("IV is not 8 octets", "parameters");
                }
            }
        }
Esempio n. 12
0
        private Zone SignWithNSec3(DateTime inception, DateTime expiration, List <DnsKeyRecord> zoneSigningKeys, List <DnsKeyRecord> keySigningKeys, NSec3HashAlgorithm nsec3Algorithm, int nsec3Iterations, byte[] nsec3Salt, bool nsec3OptOut)
        {
            var soaRecord         = _records.OfType <SoaRecord>().First();
            var subZoneNameserver = _records.Where(x => (x.RecordType == RecordType.Ns) && (x.Name != Name)).ToList();
            var subZones          = subZoneNameserver.Select(x => x.Name).Distinct().ToList();
            var unsignedRecords   = _records.Where(x => subZones.Any(y => x.Name.IsSubDomainOf(y))).ToList();           // glue records

            if (nsec3OptOut)
            {
                unsignedRecords = unsignedRecords.Union(subZoneNameserver.Where(x => !_records.Any(y => (y.RecordType == RecordType.Ds) && (y.Name == x.Name)))).ToList();                 // delegations without DS record
            }
            var recordsByName = _records.Except(unsignedRecords).Union(zoneSigningKeys).Union(keySigningKeys).GroupBy(x => x.Name).Select(x => new Tuple <DomainName, List <DnsRecordBase> >(x.Key, x.OrderBy(y => y.RecordType == RecordType.Soa ? -1 : (int)y.RecordType).ToList())).OrderBy(x => x.Item1).ToList();

            byte nsec3RecordFlags = (byte)(nsec3OptOut ? 1 : 0);

            Zone res = new Zone(Name, Count * 3);
            List <NSec3Record> nSec3Records = new List <NSec3Record>(Count);

            if (nsec3Salt == null)
            {
                nsec3Salt = SecureRandom.GetSeed(8);
            }

            recordsByName[0].Item2.Add(new NSec3ParamRecord(soaRecord.Name, soaRecord.RecordClass, 0, nsec3Algorithm, 0, (ushort)nsec3Iterations, nsec3Salt));

            HashSet <DomainName> allNames = new HashSet <DomainName>();

            for (int i = 0; i < recordsByName.Count; i++)
            {
                List <RecordType> recordTypes = new List <RecordType>();

                DomainName currentName = recordsByName[i].Item1;

                foreach (var recordsByType in recordsByName[i].Item2.GroupBy(x => x.RecordType))
                {
                    List <DnsRecordBase> records = recordsByType.ToList();

                    recordTypes.Add(recordsByType.Key);
                    res.AddRange(records);

                    // do not sign nameserver delegations for sub zones
                    if ((records[0].RecordType == RecordType.Ns) && (currentName != Name))
                    {
                        continue;
                    }

                    recordTypes.Add(RecordType.RrSig);

                    foreach (var key in zoneSigningKeys)
                    {
                        res.Add(new RrSigRecord(records, key, inception, expiration));
                    }
                    if (records[0].RecordType == RecordType.DnsKey)
                    {
                        foreach (var key in keySigningKeys)
                        {
                            res.Add(new RrSigRecord(records, key, inception, expiration));
                        }
                    }
                }

                byte[] hash = recordsByName[i].Item1.GetNSec3Hash(nsec3Algorithm, nsec3Iterations, nsec3Salt);
                nSec3Records.Add(new NSec3Record(DomainName.ParseFromMasterfile(hash.ToBase32HexString()) + Name, soaRecord.RecordClass, soaRecord.NegativeCachingTTL, nsec3Algorithm, nsec3RecordFlags, (ushort)nsec3Iterations, nsec3Salt, hash, recordTypes));

                allNames.Add(currentName);
                for (int j = currentName.LabelCount - Name.LabelCount; j > 0; j--)
                {
                    DomainName possibleNonTerminal = currentName.GetParentName(j);

                    if (!allNames.Contains(possibleNonTerminal))
                    {
                        hash = possibleNonTerminal.GetNSec3Hash(nsec3Algorithm, nsec3Iterations, nsec3Salt);
                        nSec3Records.Add(new NSec3Record(DomainName.ParseFromMasterfile(hash.ToBase32HexString()) + Name, soaRecord.RecordClass, soaRecord.NegativeCachingTTL, nsec3Algorithm, nsec3RecordFlags, (ushort)nsec3Iterations, nsec3Salt, hash, new List <RecordType>()));

                        allNames.Add(possibleNonTerminal);
                    }
                }
            }

            nSec3Records = nSec3Records.OrderBy(x => x.Name).ToList();

            byte[] firstNextHashedOwnerName = nSec3Records[0].NextHashedOwnerName;

            for (int i = 1; i < nSec3Records.Count; i++)
            {
                nSec3Records[i - 1].NextHashedOwnerName = nSec3Records[i].NextHashedOwnerName;
            }

            nSec3Records[nSec3Records.Count - 1].NextHashedOwnerName = firstNextHashedOwnerName;

            foreach (var nSec3Record in nSec3Records)
            {
                res.Add(nSec3Record);

                foreach (var key in zoneSigningKeys)
                {
                    res.Add(new RrSigRecord(new List <DnsRecordBase>()
                    {
                        nSec3Record
                    }, key, inception, expiration));
                }
            }

            res.AddRange(unsignedRecords);

            return(res);
        }
Esempio n. 13
0
 public override void GetBytes(byte[] data)
 {
     _rng.NextBytes(data);
     _rng.SetSeed(SecureRandom.GetSeed(16));
 }
Esempio n. 14
0
 public static byte[] GetRandomBytes(int length)
 {
     byte[] result = SecureRandom.GetSeed(length);
     return(result);
 }
Esempio n. 15
0
            internal RecipientInfo ToRecipientInfo(
                KeyParameter key)
            {
                byte[] keyBytes = key.GetKey();

                if (pubKey != null)
                {
                    IWrapper keyWrapper = Helper.CreateWrapper(keyEncAlg.ObjectID.Id);

                    keyWrapper.Init(true, pubKey);

                    Asn1OctetString encKey = new DerOctetString(
                        keyWrapper.Wrap(keyBytes, 0, keyBytes.Length));

                    RecipientIdentifier recipId;
                    if (cert != null)
                    {
                        TbsCertificateStructure tbs = TbsCertificateStructure.GetInstance(
                            Asn1Object.FromByteArray(cert.GetTbsCertificate()));

                        Asn1.Cms.IssuerAndSerialNumber encSid = new Asn1.Cms.IssuerAndSerialNumber(
                            tbs.Issuer, tbs.SerialNumber.Value);

                        recipId = new RecipientIdentifier(encSid);
                    }
                    else
                    {
                        recipId = new RecipientIdentifier(subKeyId);
                    }

                    return(new RecipientInfo(new KeyTransRecipientInfo(recipId, keyEncAlg, encKey)));
                }
                else if (originator != null)
                {
                    IWrapper keyWrapper = Helper.CreateWrapper(
                        DerObjectIdentifier.GetInstance(
                            Asn1Sequence.GetInstance(keyEncAlg.Parameters)[0]).Id);

                    keyWrapper.Init(true, secKey);

                    Asn1OctetString encKey = new DerOctetString(
                        keyWrapper.Wrap(keyBytes, 0, keyBytes.Length));

                    RecipientEncryptedKey rKey = new RecipientEncryptedKey(
                        new KeyAgreeRecipientIdentifier(
                            new Asn1.Cms.IssuerAndSerialNumber(
                                PrincipalUtilities.GetIssuerX509Principal(cert),
                                cert.SerialNumber)),
                        encKey);

                    return(new RecipientInfo(
                               new KeyAgreeRecipientInfo(originator, ukm, keyEncAlg, new DerSequence(rKey))));
                }
                else if (derivationAlg != null)
                {
                    string   rfc3211WrapperName = Helper.GetRfc3211WrapperName(secKeyAlgorithm);
                    IWrapper keyWrapper         = Helper.CreateWrapper(rfc3211WrapperName);


                    // Note: In Java build, the IV is automatically generated in JCE layer
                    int    ivLength = rfc3211WrapperName.StartsWith("DESEDE") ? 8 : 16;
                    byte[] iv       = SecureRandom.GetSeed(ivLength);


                    ICipherParameters parameters = new ParametersWithIV(secKey, iv);
                    keyWrapper.Init(true, parameters);

                    Asn1OctetString encKey = new DerOctetString(
                        keyWrapper.Wrap(keyBytes, 0, keyBytes.Length));

//					byte[] iv = keyWrapper.GetIV();

                    DerSequence seq = new DerSequence(
                        new DerObjectIdentifier(secKeyAlgorithm),
                        new DerOctetString(iv));

                    keyEncAlg = new AlgorithmIdentifier(PkcsObjectIdentifiers.IdAlgPwriKek, seq);

                    return(new RecipientInfo(new PasswordRecipientInfo(derivationAlg, keyEncAlg, encKey)));
                }
                else
                {
                    IWrapper keyWrapper = Helper.CreateWrapper(keyEncAlg.ObjectID.Id);

                    keyWrapper.Init(true, secKey);

                    Asn1OctetString encKey = new DerOctetString(
                        keyWrapper.Wrap(keyBytes, 0, keyBytes.Length));

                    return(new RecipientInfo(new KekRecipientInfo(secKeyId, keyEncAlg, encKey)));
                }
            }
 private static byte[] GetChallege()
 {
     return(SecureRandom.GetSeed(16));
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="KeyGenerator"/> class
 /// with the specified key size.
 /// </summary>
 /// <remarks>Following key sizes are supported:
 /// - 192
 /// - 224
 /// - 239
 /// - 256 (default)
 /// - 384
 /// - 521</remarks>
 /// <param name="keySize">The key size.</param>
 public KeyGenerator(int keySize)
     : this(keySize, SecureRandom.GetSeed(32))
 {
 }
Esempio n. 18
0
 public BouncyCastleRandomNumberGenerator()
 {
     _rng = new SecureRandom(new DigestRandomGenerator(new Sha512Digest()));
     _rng.SetSeed(SecureRandom.GetSeed(32));
 }