Esempio n. 1
0
        // GenerateRsaKeyPair(1024)
        public static Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair GenerateRsaKeyPair(int strength)
        {
            Org.BouncyCastle.Crypto.Generators.RsaKeyPairGenerator gen   = new Org.BouncyCastle.Crypto.Generators.RsaKeyPairGenerator();
            Org.BouncyCastle.Security.SecureRandom          secureRandom = new Org.BouncyCastle.Security.SecureRandom(new Org.BouncyCastle.Crypto.Prng.CryptoApiRandomGenerator());
            Org.BouncyCastle.Crypto.KeyGenerationParameters keyGenParam  = new Org.BouncyCastle.Crypto.KeyGenerationParameters(secureRandom, strength);

            gen.Init(keyGenParam);

            Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair kp = gen.GenerateKeyPair();
            return(kp);
        } // End Function GenerateRsaKeyPair
Esempio n. 2
0
        public static Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair GenerateRsaKeyPair(Org.BouncyCastle.Security.SecureRandom random, int strength)
        {
            Org.BouncyCastle.Crypto.Generators.RsaKeyPairGenerator gen = new Org.BouncyCastle.Crypto.Generators.RsaKeyPairGenerator();

            Org.BouncyCastle.Crypto.KeyGenerationParameters keyGenParam =
                new Org.BouncyCastle.Crypto.KeyGenerationParameters(random, strength);

            gen.Init(keyGenParam);

            Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair kp = gen.GenerateKeyPair();
            return(kp);
        } // End Sub GenerateRsaKeyPair
        } // End Function GenerateGostKeyPair

        public static Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair GenerateRsaKeyPair(
            int length
            , Org.BouncyCastle.Security.SecureRandom secureRandom
            )
        {
            Org.BouncyCastle.Crypto.KeyGenerationParameters keygenParam =
                new Org.BouncyCastle.Crypto.KeyGenerationParameters(secureRandom, length);

            Org.BouncyCastle.Crypto.Generators.RsaKeyPairGenerator keyGenerator =
                new Org.BouncyCastle.Crypto.Generators.RsaKeyPairGenerator();
            keyGenerator.Init(keygenParam);

            return(keyGenerator.GenerateKeyPair());
        } // End Function GenerateRsaKeyPair
Esempio n. 4
0
        // https://stackoverflow.com/questions/6128541/bouncycastle-privatekey-to-x509certificate2-privatekey
        public static Org.BouncyCastle.X509.X509Certificate CreateX509Cert(string certName)
        {
            var keypairgen = new Org.BouncyCastle.Crypto.Generators.RsaKeyPairGenerator();

            keypairgen.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(
                                new Org.BouncyCastle.Security.SecureRandom(
                                    new Org.BouncyCastle.Crypto.Prng.CryptoApiRandomGenerator()
                                    )
                                , 1024
                                )
                            );

            var keypair = keypairgen.GenerateKeyPair();

            var gen = new Org.BouncyCastle.X509.X509V3CertificateGenerator();


            var CN = new Org.BouncyCastle.Asn1.X509.X509Name("CN=" + certName);
            var SN = Org.BouncyCastle.Math.BigInteger.ProbablePrime(120, new Random());

            gen.SetSerialNumber(SN);
            gen.SetSubjectDN(CN);
            gen.SetIssuerDN(CN);
            gen.SetNotAfter(DateTime.Now.AddYears(1));
            gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0)));
            gen.SetSignatureAlgorithm("MD5WithRSA");
            gen.SetPublicKey(keypair.Public);

            gen.AddExtension(
                Org.BouncyCastle.Asn1.X509.X509Extensions.AuthorityKeyIdentifier.Id,
                false,
                new Org.BouncyCastle.Asn1.X509.AuthorityKeyIdentifier(
                    Org.BouncyCastle.X509.SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keypair.Public),
                    new Org.BouncyCastle.Asn1.X509.GeneralNames(new Org.BouncyCastle.Asn1.X509.GeneralName(CN)),
                    SN
                    ));

            gen.AddExtension(
                Org.BouncyCastle.Asn1.X509.X509Extensions.ExtendedKeyUsage.Id,
                false,
                new Org.BouncyCastle.Asn1.X509.ExtendedKeyUsage(new ArrayList()
            {
                new Org.BouncyCastle.Asn1.DerObjectIdentifier("1.3.6.1.5.5.7.3.1")
            }));

            Org.BouncyCastle.X509.X509Certificate newCert = gen.Generate(keypair.Private);


            return(newCert);
        }
Esempio n. 5
0
        public void RsaFuzzTest()
        {
            // Create many RSA keys, encode them in PKCS8, verify the Pkcs8 class can decode them correctly.
            // This test does take a few (possibly 10s of) seconds, longer than most unit tests.
            for (int i = 0; i < 1000; i++)
            {
                // This SecureRandom constructor is deprecated,
                // but is the easiest way to create a deterministic SecureRandom.
#pragma warning disable CS0618
                var rnd = new Org.BouncyCastle.Security.SecureRandom(new byte[] { (byte)(i & 0xff), (byte)((i >> 8) & 0xff) });
#pragma warning restore CS0618
                var rsa = new Org.BouncyCastle.Crypto.Generators.RsaKeyPairGenerator();
                // 384 is the shortest valid key length. Use this for speed.
                rsa.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(rnd, 384));
                var keys           = rsa.GenerateKeyPair();
                var pkcs8Generator = new Org.BouncyCastle.OpenSsl.Pkcs8Generator(keys.Private);
                var pem            = pkcs8Generator.Generate();
                var ms             = new System.IO.MemoryStream();
                var stWriter       = new System.IO.StreamWriter(ms);
                var pemWriter      = new Org.BouncyCastle.OpenSsl.PemWriter(stWriter);
                pemWriter.WriteObject(pem);
                stWriter.Close();
                var pkcs8         = System.Text.Encoding.ASCII.GetString(ms.ToArray());
                var rsaParameters = Pkcs8.DecodeRsaParameters(pkcs8);
                var key           = RSA.Create();
                try
                {
                    // Test that the parameters can be imported.
                    // Throws CryptographicException if the rsaParameters is invalid
                    key.ImportParameters(rsaParameters);
                }
                catch (CryptographicException e)
                {
                    // Fails in iteration 8 without the Pkcs8 fix in PR#937
                    Assert.True(false, $"Failed in iteration {i}: {e}");
                }
                // Check that all the parameters exported are equal to the originally created parameters
                var exportedParams = key.ExportParameters(true);
                var privateKey     = (Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters)keys.Private;
                Assert.Equal(privateKey.P.ToByteArrayUnsigned(), Pkcs8.TrimLeadingZeroes(exportedParams.P, false));
                Assert.Equal(privateKey.Q.ToByteArrayUnsigned(), Pkcs8.TrimLeadingZeroes(exportedParams.Q, false));
                Assert.Equal(privateKey.DP.ToByteArrayUnsigned(), Pkcs8.TrimLeadingZeroes(exportedParams.DP, false));
                Assert.Equal(privateKey.DQ.ToByteArrayUnsigned(), Pkcs8.TrimLeadingZeroes(exportedParams.DQ, false));
                var publicKey = (Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters)keys.Public;
                Assert.Equal(publicKey.Exponent.ToByteArrayUnsigned(), Pkcs8.TrimLeadingZeroes(exportedParams.Exponent, false));
                Assert.Equal(publicKey.Modulus.ToByteArrayUnsigned(), Pkcs8.TrimLeadingZeroes(exportedParams.Modulus, false));
            }
        }
Esempio n. 6
0
        // http://stackoverflow.com/questions/36942094/how-can-i-generate-a-self-signed-cert-without-using-obsolete-bouncycastle-1-7-0
        public static System.Security.Cryptography.X509Certificates.X509Certificate2 CreateX509Cert2(string certName)
        {
            var keypairgen = new Org.BouncyCastle.Crypto.Generators.RsaKeyPairGenerator();

            keypairgen.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(
                                new Org.BouncyCastle.Security.SecureRandom(
                                    new Org.BouncyCastle.Crypto.Prng.CryptoApiRandomGenerator()
                                    )
                                , 1024
                                )
                            );

            Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keypair = keypairgen.GenerateKeyPair();

            // --- Until here we generate a keypair



            var random = new Org.BouncyCastle.Security.SecureRandom(
                new Org.BouncyCastle.Crypto.Prng.CryptoApiRandomGenerator()
                );


            // SHA1WITHRSA
            // SHA256WITHRSA
            // SHA384WITHRSA
            // SHA512WITHRSA

            // SHA1WITHECDSA
            // SHA224WITHECDSA
            // SHA256WITHECDSA
            // SHA384WITHECDSA
            // SHA512WITHECDSA

            Org.BouncyCastle.Crypto.ISignatureFactory signatureFactory =
                new Org.BouncyCastle.Crypto.Operators.Asn1SignatureFactory("SHA512WITHRSA", keypair.Private, random)
            ;



            var gen = new Org.BouncyCastle.X509.X509V3CertificateGenerator();


            var CN = new Org.BouncyCastle.Asn1.X509.X509Name("CN=" + certName);
            var SN = Org.BouncyCastle.Math.BigInteger.ProbablePrime(120, new Random());

            gen.SetSerialNumber(SN);
            gen.SetSubjectDN(CN);
            gen.SetIssuerDN(CN);
            gen.SetNotAfter(DateTime.Now.AddYears(1));
            gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0)));
            gen.SetPublicKey(keypair.Public);


            // -- Are these necessary ?

            // public static readonly DerObjectIdentifier AuthorityKeyIdentifier = new DerObjectIdentifier("2.5.29.35");
            // OID value: 2.5.29.35
            // OID description: id-ce-authorityKeyIdentifier
            // This extension may be used either as a certificate or CRL extension.
            // It identifies the public key to be used to verify the signature on this certificate or CRL.
            // It enables distinct keys used by the same CA to be distinguished (e.g., as key updating occurs).


            // http://stackoverflow.com/questions/14930381/generating-x509-certificate-using-bouncy-castle-java
            gen.AddExtension(
                Org.BouncyCastle.Asn1.X509.X509Extensions.AuthorityKeyIdentifier.Id,
                false,
                new Org.BouncyCastle.Asn1.X509.AuthorityKeyIdentifier(
                    Org.BouncyCastle.X509.SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keypair.Public),
                    new Org.BouncyCastle.Asn1.X509.GeneralNames(new Org.BouncyCastle.Asn1.X509.GeneralName(CN)),
                    SN
                    ));

            // OID value: 1.3.6.1.5.5.7.3.1
            // OID description: Indicates that a certificate can be used as an SSL server certificate.
            gen.AddExtension(
                Org.BouncyCastle.Asn1.X509.X509Extensions.ExtendedKeyUsage.Id,
                false,
                new Org.BouncyCastle.Asn1.X509.ExtendedKeyUsage(new ArrayList()
            {
                new Org.BouncyCastle.Asn1.DerObjectIdentifier("1.3.6.1.5.5.7.3.1")
            }));

            // -- End are these necessary ?

            Org.BouncyCastle.X509.X509Certificate bouncyCert = gen.Generate(signatureFactory);

            byte[] ba = bouncyCert.GetEncoded();
            System.Security.Cryptography.X509Certificates.X509Certificate2 msCert = new System.Security.Cryptography.X509Certificates.X509Certificate2(ba);
            return(msCert);
        }
Esempio n. 7
0
        /// <summary>
        ///   Creates a new signing key pair
        /// </summary>
        /// <param name="name">The name of the key or zone</param>
        /// <param name="recordClass">The record class of the DnsKeyRecord</param>
        /// <param name="timeToLive">The TTL in seconds to the DnsKeyRecord</param>
        /// <param name="flags">The Flags of the DnsKeyRecord</param>
        /// <param name="protocol">The protocol version</param>
        /// <param name="algorithm">The key algorithm</param>
        /// <param name="keyStrength">The key strength or 0 for default strength</param>
        /// <returns></returns>
        public static KeyPairRecord CreateSigningKey(DnsSecAlgorithm algorithm, DnsKeyFlags flags, int keyStrength = 0)
        {
            // Found in DnsKeyRecord.CreateSigningKey
            KeyPairRecord rec = new KeyPairRecord();

            rec.Flags     = flags;
            rec.Algorithm = algorithm;

            Org.BouncyCastle.Security.SecureRandom _secureRandom =
                new Org.BouncyCastle.Security.SecureRandom(new Org.BouncyCastle.Crypto.Prng.CryptoApiRandomGenerator());

            // https://csharp.hotexamples.com/examples/Org.BouncyCastle.Crypto.Generators/DsaKeyPairGenerator/GenerateKeyPair/php-dsakeypairgenerator-generatekeypair-method-examples.html

            switch (algorithm)
            {
            case DnsSecAlgorithm.RsaSha1:
            case DnsSecAlgorithm.RsaSha1Nsec3Sha1:
            case DnsSecAlgorithm.RsaSha256:
            case DnsSecAlgorithm.RsaSha512:
                if (keyStrength == 0)
                {
                    keyStrength = (flags == (DnsKeyFlags.Zone | DnsKeyFlags.SecureEntryPoint)) ? 2048 : 1024;
                }

                Org.BouncyCastle.Crypto.Generators.RsaKeyPairGenerator rsaKeyGen = new Org.BouncyCastle.Crypto.Generators.RsaKeyPairGenerator();
                rsaKeyGen.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(_secureRandom, keyStrength));
                var rsaKey = rsaKeyGen.GenerateKeyPair();
                rec.KeyPair    = rsaKey;
                rec.PrivateKey = Org.BouncyCastle.Pkcs.PrivateKeyInfoFactory.CreatePrivateKeyInfo(rsaKey.Private).GetDerEncoded();
                var rsaPublicKey = (Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters)rsaKey.Public;
                var rsaExponent  = rsaPublicKey.Exponent.ToByteArrayUnsigned();
                var rsaModulus   = rsaPublicKey.Modulus.ToByteArrayUnsigned();

                int offset = 1;
                if (rsaExponent.Length > 255)
                {
                    rec.PublicKey = new byte[3 + rsaExponent.Length + rsaModulus.Length];
                    EncodeUShort(rec.PublicKey, ref offset, (ushort)rec.PublicKey.Length);
                }
                else
                {
                    rec.PublicKey    = new byte[1 + rsaExponent.Length + rsaModulus.Length];
                    rec.PublicKey[0] = (byte)rsaExponent.Length;
                }
                EncodeByteArray(rec.PublicKey, ref offset, rsaExponent);
                EncodeByteArray(rec.PublicKey, ref offset, rsaModulus);
                break;

            case DnsSecAlgorithm.Dsa:
            case DnsSecAlgorithm.DsaNsec3Sha1:
                if (keyStrength == 0)
                {
                    keyStrength = 1024;
                }

                Org.BouncyCastle.Crypto.Generators.DsaParametersGenerator dsaParamsGen = new Org.BouncyCastle.Crypto.Generators.DsaParametersGenerator();
                dsaParamsGen.Init(keyStrength, 12, _secureRandom);
                Org.BouncyCastle.Crypto.Generators.DsaKeyPairGenerator dsaKeyGen = new Org.BouncyCastle.Crypto.Generators.DsaKeyPairGenerator();
                dsaKeyGen.Init(new Org.BouncyCastle.Crypto.Parameters.DsaKeyGenerationParameters(_secureRandom, dsaParamsGen.GenerateParameters()));
                Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair dsaKey = dsaKeyGen.GenerateKeyPair();
                rec.KeyPair = dsaKey;

                rec.PrivateKey = Org.BouncyCastle.Pkcs.PrivateKeyInfoFactory.CreatePrivateKeyInfo(dsaKey.Private).GetDerEncoded();
                var dsaPublicKey = (Org.BouncyCastle.Crypto.Parameters.DsaPublicKeyParameters)dsaKey.Public;

                byte[] dsaY = dsaPublicKey.Y.ToByteArrayUnsigned();
                byte[] dsaP = dsaPublicKey.Parameters.P.ToByteArrayUnsigned();
                byte[] dsaQ = dsaPublicKey.Parameters.Q.ToByteArrayUnsigned();
                byte[] dsaG = dsaPublicKey.Parameters.G.ToByteArrayUnsigned();
                byte   dsaT = (byte)((dsaY.Length - 64) / 8);

                rec.PublicKey    = new byte[21 + 3 * dsaY.Length];
                rec.PublicKey[0] = dsaT;
                dsaQ.CopyTo(rec.PublicKey, 1);
                dsaP.CopyTo(rec.PublicKey, 21);
                dsaG.CopyTo(rec.PublicKey, 21 + dsaY.Length);
                dsaY.CopyTo(rec.PublicKey, 21 + 2 * dsaY.Length);
                break;

            case DnsSecAlgorithm.EccGost:
                Org.BouncyCastle.Crypto.Parameters.ECDomainParameters gostEcDomainParameters = Org.BouncyCastle.Asn1.CryptoPro.ECGost3410NamedCurves.GetByOid(Org.BouncyCastle.Asn1.CryptoPro.CryptoProObjectIdentifiers.GostR3410x2001CryptoProA);

                var gostKeyGen = new Org.BouncyCastle.Crypto.Generators.ECKeyPairGenerator();
                gostKeyGen.Init(new Org.BouncyCastle.Crypto.Parameters.ECKeyGenerationParameters(gostEcDomainParameters, _secureRandom));

                var gostKey = gostKeyGen.GenerateKeyPair();
                rec.KeyPair    = gostKey;
                rec.PrivateKey = Org.BouncyCastle.Pkcs.PrivateKeyInfoFactory.CreatePrivateKeyInfo(gostKey.Private).GetDerEncoded();
                var gostPublicKey = (Org.BouncyCastle.Crypto.Parameters.ECPublicKeyParameters)gostKey.Public;

                rec.PublicKey = new byte[64];

                // gostPublicKey.Q.X.ToBigInteger().ToByteArrayUnsigned().CopyTo(publicKey, 32);
                gostPublicKey.Q.AffineXCoord.ToBigInteger().ToByteArrayUnsigned().CopyTo(rec.PublicKey, 32);
                // gostPublicKey.Q.Y.ToBigInteger().ToByteArrayUnsigned().CopyTo(publicKey, 0);
                gostPublicKey.Q.AffineYCoord.ToBigInteger().ToByteArrayUnsigned().CopyTo(rec.PublicKey, 0);

                System.Array.Reverse(rec.PublicKey);
                break;

            case DnsSecAlgorithm.EcDsaP256Sha256:
            case DnsSecAlgorithm.EcDsaP384Sha384:
                int ecDsaDigestSize;
                Org.BouncyCastle.Asn1.X9.X9ECParameters ecDsaCurveParameter;

                if (algorithm == DnsSecAlgorithm.EcDsaP256Sha256)
                {
                    ecDsaDigestSize     = new Org.BouncyCastle.Crypto.Digests.Sha256Digest().GetDigestSize();
                    ecDsaCurveParameter = Org.BouncyCastle.Asn1.Nist.NistNamedCurves.GetByOid(Org.BouncyCastle.Asn1.Sec.SecObjectIdentifiers.SecP256r1);
                }
                else
                {
                    ecDsaDigestSize     = new Org.BouncyCastle.Crypto.Digests.Sha384Digest().GetDigestSize();
                    ecDsaCurveParameter = Org.BouncyCastle.Asn1.Nist.NistNamedCurves.GetByOid(Org.BouncyCastle.Asn1.Sec.SecObjectIdentifiers.SecP384r1);
                }

                Org.BouncyCastle.Crypto.Parameters.ECDomainParameters ecDsaP384EcDomainParameters = new Org.BouncyCastle.Crypto.Parameters.ECDomainParameters(
                    ecDsaCurveParameter.Curve,
                    ecDsaCurveParameter.G,
                    ecDsaCurveParameter.N,
                    ecDsaCurveParameter.H,
                    ecDsaCurveParameter.GetSeed());

                var ecDsaKeyGen = new Org.BouncyCastle.Crypto.Generators.ECKeyPairGenerator();
                ecDsaKeyGen.Init(new Org.BouncyCastle.Crypto.Parameters.ECKeyGenerationParameters(ecDsaP384EcDomainParameters, _secureRandom));

                Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair ecDsaKey = ecDsaKeyGen.GenerateKeyPair();
                rec.KeyPair = ecDsaKey;

                rec.PrivateKey = Org.BouncyCastle.Pkcs.PrivateKeyInfoFactory.CreatePrivateKeyInfo(ecDsaKey.Private).GetDerEncoded();
                var ecDsaPublicKey = (Org.BouncyCastle.Crypto.Parameters.ECPublicKeyParameters)ecDsaKey.Public;

                rec.PublicKey = new byte[ecDsaDigestSize * 2];
                // ecDsaPublicKey.Q.X.ToBigInteger().ToByteArrayUnsigned().CopyTo(publicKey, 0);
                ecDsaPublicKey.Q.AffineXCoord.ToBigInteger().ToByteArrayUnsigned().CopyTo(rec.PublicKey, 0);
                // ecDsaPublicKey.Q.Y.ToBigInteger().ToByteArrayUnsigned().CopyTo(publicKey, ecDsaDigestSize);
                ecDsaPublicKey.Q.AffineYCoord.ToBigInteger().ToByteArrayUnsigned().CopyTo(rec.PublicKey, ecDsaDigestSize);
                break;

            default:
                throw new System.NotSupportedException();
            }

            // return new DnsKeyRecord(name, recordClass, timeToLive, flags, protocol, algorithm, rec.PublicKey, rec.PrivateKey);
            return(rec);
        }