コード例 #1
0
        private X509Certificate2 ConvertCertificate(X509Certificate certificate)
        {
            var    store            = new Pkcs12Store();
            string friendlyName     = certificate.SubjectDN.ToString();
            var    certificateEntry = new X509CertificateEntry(certificate);

            store.SetCertificateEntry(friendlyName, certificateEntry);
            store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(subjectKeyPair.Private), new[] { certificateEntry });

            const string password = "******";
            var          stream   = new MemoryStream();

            store.Save(stream, password.ToCharArray(), random);

            return(new X509Certificate2(stream.ToArray(), password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable));
        }
コード例 #2
0
        private static X509Certificate2 withPrivateKey(X509Certificate certificate, AsymmetricKeyParameter privateKey)
        {
            const string password = "******";
            var          store    = new Pkcs12Store();
            var          entry    = new X509CertificateEntry(certificate);

            store.SetCertificateEntry(certificate.SubjectDN.ToString(), entry);

            store.SetKeyEntry(certificate.SubjectDN.ToString(), new AsymmetricKeyEntry(privateKey), new[] { entry });
            using (var ms = new MemoryStream())
            {
                store.Save(ms, password.ToCharArray(), new SecureRandom(new CryptoApiRandomGenerator()));

                return(new X509Certificate2(ms.ToArray(), password, X509KeyStorageFlags.Exportable));
            }
        }
コード例 #3
0
        public AsymmetricCipherKeyPair GenerateCertificate(string subjectName, TimeSpan validFor, string path, string password)
        {
            SecureRandom random = GetRandom();

            var certificateGenerator = new X509V3CertificateGenerator();

            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);
            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);

            var subjectDN = new X509Name(subjectName);
            var issuerDN  = subjectDN;

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = notBefore.Add(validFor);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            var keyGenerationParameters = new KeyGenerationParameters(random, strength);

            var keyPairGenerator = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            AsymmetricCipherKeyPair subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            var issuerKeyPair = subjectKeyPair;
            var certificate   = certificateGenerator.Generate(issuerKeyPair.Private, random);

            var    store            = new Pkcs12Store();
            string friendlyName     = certificate.SubjectDN.ToString();
            var    certificateEntry = new X509CertificateEntry(certificate);

            store.SetCertificateEntry(friendlyName, certificateEntry);
            var stream = new MemoryStream();

            store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(subjectKeyPair.Private), new[] { certificateEntry });
            store.Save(stream, password.ToCharArray(), random);
            File.WriteAllBytes(path, stream.ToArray());
            return(subjectKeyPair);
        }
コード例 #4
0
        public static void GenerateNewCertificate(string name, Stream stream)
        {
            var kpGen = new RsaKeyPairGenerator();

            kpGen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 1024));

            AsymmetricCipherKeyPair keyPair = kpGen.GenerateKeyPair();
            var        gen             = new X509V3CertificateGenerator();
            var        certificateName = new X509Name("CN=" + name);
            BigInteger serialNumber    = BigInteger.ProbablePrime(120, new Random());

            gen.SetSerialNumber(serialNumber);
            gen.SetSubjectDN(certificateName);
            gen.SetIssuerDN(certificateName);
            gen.SetNotAfter(SystemTime.UtcNow.AddYears(100));
            gen.SetNotBefore(SystemTime.UtcNow.AddDays(-1));
            gen.SetSignatureAlgorithm("SHA256WithRSAEncryption");
            gen.SetPublicKey(keyPair.Public);

            gen.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, false,
                             new AuthorityKeyIdentifier(
                                 SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public),
                                 new GeneralNames(new GeneralName(certificateName)), serialNumber));

            X509Certificate newCert = gen.Generate(keyPair.Private);

            var newStore = new Pkcs12Store();

            var certEntry = new X509CertificateEntry(newCert);

            newStore.SetCertificateEntry(
                Environment.MachineName,
                certEntry
                );

            newStore.SetKeyEntry(
                Environment.MachineName,
                new AsymmetricKeyEntry(keyPair.Private),
                new[] { certEntry }
                );

            newStore.Save(
                stream,
                new char[0],
                new SecureRandom(new CryptoApiRandomGenerator())
                );
        }
コード例 #5
0
        /// <summary>
        /// Exports the certificate as a pfx file, optionally including the private key.
        /// </summary>
        /// <param name="includePrivateKey">If true, the private key is included.  If the private key is included, you should consider setting a password.</param>
        /// <param name="password">If non-null, a password is required to use the resulting pfx file.</param>
        /// <returns></returns>
        public byte[] GetPfx(bool includePrivateKey, string password)
        {
            string               subject     = GetSubjectName();
            Pkcs12Store          pkcs12Store = new Pkcs12Store();
            X509CertificateEntry certEntry   = new X509CertificateEntry(cert);

            pkcs12Store.SetCertificateEntry(subject, certEntry);
            if (includePrivateKey)
            {
                pkcs12Store.SetKeyEntry(subject, new AsymmetricKeyEntry(privateKey), new[] { certEntry });
            }
            using (MemoryStream pfxStream = new MemoryStream())
            {
                pkcs12Store.Save(pfxStream, password == null ? null : password.ToCharArray(), CertMaker.secureRandom);
                return(pfxStream.ToArray());
            }
        }
コード例 #6
0
ファイル: CertificateHelper.cs プロジェクト: sitangruan/nini
        public static void SaveToFile(
            X509Certificate newCert,
            AsymmetricCipherKeyPair kp,
            string filePath,
            string certAlias,
            string password)
        {
            var newStore  = new Pkcs12Store();
            var certEntry = new X509CertificateEntry(newCert);

            newStore.SetCertificateEntry(certAlias, certEntry);
            newStore.SetKeyEntry(certAlias, new AsymmetricKeyEntry(kp.Private), new[] { certEntry });
            using (var certFile = File.Create(filePath))
            {
                newStore.Save(certFile, password.ToCharArray(), new SecureRandom(new VmpcRandomGenerator()));
            }
        }
コード例 #7
0
        internal static string SaveP12(AsymmetricKeyParameter privateKey, X509Certificate cert, string keyFile, string password, string alias)
        {
            // Use the FIPS-140 system prng
            SecureRandom random = new SecureRandom(new CryptoApiRandomGenerator());

            // Build PKCS#12
            Pkcs12StoreBuilder p12  = new Pkcs12StoreBuilder();
            Pkcs12Store        pkcs = p12.Build();

            pkcs.SetKeyEntry(alias, new AsymmetricKeyEntry(privateKey), new X509CertificateEntry[] { new X509CertificateEntry(cert) });

            Stream stream = new FileStream(keyFile, FileMode.Create);

            pkcs.Save(stream, password.ToCharArray(), random);
            stream.Close();
            return(alias);
        }
コード例 #8
0
        public static byte[] ExportCertificate(this X509Certificate x509Certificate, SecureString password, AsymmetricKeyParameter privateKey, string alias = "Certificate")
        {
            var pkcs12Store = new Pkcs12Store();

            var x509CertificateEntry = new X509CertificateEntry(x509Certificate);

            pkcs12Store.SetCertificateEntry(alias, x509CertificateEntry);

            pkcs12Store.SetKeyEntry(alias, new AsymmetricKeyEntry(privateKey), new[] { x509CertificateEntry });

            using (var ms = new MemoryStream())
            {
                pkcs12Store.Save(ms, password.ToCharArray(), new SecureRandom(new CryptoApiRandomGenerator()));

                return(ms.ToArray());
            }
        }
コード例 #9
0
        private void keyStoreTest(
            IAsymmetricKeyParameter sKey,
            IAsymmetricKeyParameter vKey)
//	        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, NoSuchProviderException, SignatureException, InvalidKeyException, UnrecoverableKeyException
        {
            //
            // keystore test
            //
//			KeyStore ks = KeyStore.GetInstance("JKS");
//			ks.Load(null, null);
            Pkcs12StoreBuilder ksBuilder = new Pkcs12StoreBuilder();
            Pkcs12Store        ks        = ksBuilder.Build();

            //
            // create the certificate - version 3
            //
            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);
            certGen.SetIssuerDN(new X509Name("CN=Test"));
            certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
            certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
            certGen.SetSubjectDN(new X509Name("CN=Test"));
            certGen.SetPublicKey(vKey);
            certGen.SetSignatureAlgorithm("GOST3411withGOST3410");

            X509Certificate      cert      = certGen.Generate(sKey);
            X509CertificateEntry certEntry = new X509CertificateEntry(cert);

//	        ks.SetKeyEntry("gost", sKey, "gost".ToCharArray(), new X509Certificate[] { cert });
            ks.SetKeyEntry("gost", new AsymmetricKeyEntry(sKey), new X509CertificateEntry[] { certEntry });

            MemoryStream bOut = new MemoryStream();

            ks.Save(bOut, "gost".ToCharArray(), new SecureRandom());

//	        ks = KeyStore.getInstance("JKS");
            ks = ksBuilder.Build();

            ks.Load(new MemoryStream(bOut.ToArray(), false), "gost".ToCharArray());

//	        IAsymmetricKeyParameter gKey = (AsymmetricKeyParameter)ks.GetKey("gost", "gost".ToCharArray());
//	        AsymmetricKeyEntry gKeyEntry = (AsymmetricKeyEntry)
            ks.GetKey("gost");
        }
コード例 #10
0
        private byte[] ConvertToPfxCore(X509Certificate2 x509, RsaPrivateCrtKeyParameters rsaParams, string pfxPassword)
        {
            var             store            = new Pkcs12Store();
            SecureRandom    random           = randomService.GenerateRandom();
            X509Certificate cert             = DotNetUtilities.FromX509Certificate(x509);
            string          friendlyName     = cert.SubjectDN.ToString();
            var             certificateEntry = new X509CertificateEntry(cert);

            store.SetCertificateEntry(friendlyName, certificateEntry);
            store.SetKeyEntry(friendlyName,
                              new AsymmetricKeyEntry(rsaParams),
                              new[] { certificateEntry });

            using var stream = new MemoryStream();
            store.Save(stream, pfxPassword.ToCharArray(), random);

            return(stream.ToArray());
        }
コード例 #11
0
        public static byte[] CreateCertificate(string cn, string password)
        {
            if (cn == null)
            {
                throw new ArgumentNullException("cn");
            }
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }
            RsaKeyPairGenerator rsaKeyPairGenerator = new RsaKeyPairGenerator();

            rsaKeyPairGenerator.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 1024));
            AsymmetricCipherKeyPair asymmetricCipherKeyPair = rsaKeyPairGenerator.GenerateKeyPair();
            BigInteger serialNumber = BigInteger.ProbablePrime(120, new Random());
            X509Name   x509Name     = new X509Name("CN=" + cn);
            X509V3CertificateGenerator x509V3CertificateGenerator = new X509V3CertificateGenerator();

            x509V3CertificateGenerator.SetSerialNumber(serialNumber);
            x509V3CertificateGenerator.SetSubjectDN(x509Name);
            x509V3CertificateGenerator.SetIssuerDN(x509Name);
            x509V3CertificateGenerator.SetNotBefore(DateTime.UtcNow.AddDays(-2.0));
            x509V3CertificateGenerator.SetNotAfter(DateTime.UtcNow.AddYears(5));
            x509V3CertificateGenerator.SetSignatureAlgorithm("MD5WithRSAEncryption");
            x509V3CertificateGenerator.SetPublicKey(asymmetricCipherKeyPair.Public);
            x509V3CertificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeID[]
            {
                KeyPurposeID.IdKPServerAuth,
                KeyPurposeID.AnyExtendedKeyUsage
            }));
            X509Certificate      cert        = x509V3CertificateGenerator.Generate(asymmetricCipherKeyPair.Private);
            X509CertificateEntry certEntry   = new X509CertificateEntry(cert);
            Pkcs12Store          pkcs12Store = new Pkcs12Store();

            pkcs12Store.SetCertificateEntry(cn, certEntry);
            pkcs12Store.SetKeyEntry(cn, new AsymmetricKeyEntry(asymmetricCipherKeyPair.Private), new X509CertificateEntry[]
            {
                new X509CertificateEntry(cert)
            });
            MemoryStream memoryStream = new MemoryStream();

            pkcs12Store.Save(memoryStream, password.ToCharArray(), new SecureRandom(new CryptoApiRandomGenerator()));
            return(memoryStream.ToArray());
        }
コード例 #12
0
        public X509Certificate2 CreateMutualAuthenticationX509(string fullSubject, DateTimeOffset validFrom, DateTimeOffset expires)
        {
            var random = GetSecureRandom();

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id, true,
                new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPClientAuth));

            // Serial Number
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random);
            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            var subjectDN = new X509Name(fullSubject);
            var subjectKeyPair = GenerateRsaKeyPair();

            var issuerDN = subjectDN;
            var issuerKeyPair = subjectKeyPair;

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            certificateGenerator.SetNotBefore(validFrom.DateTime);
            certificateGenerator.SetNotAfter(expires.DateTime);
            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            var signatureFactory = new Asn1SignatureFactory(Asn1SignatureAlgorithm, issuerKeyPair.Private, random);
            var certificate = certificateGenerator.Generate(signatureFactory);

            var store = new Pkcs12Store();
            var friendlyName = certificate.SubjectDN.ToString();
            var certificateEntry = new X509CertificateEntry(certificate);
            var keyEntry = new AsymmetricKeyEntry(subjectKeyPair.Private);

            store.SetCertificateEntry(friendlyName, certificateEntry);
            store.SetKeyEntry(friendlyName, keyEntry, new[] { certificateEntry });
            var stream = new MemoryStream();
            store.Save(stream, new char[0], random);

            var bytes = stream.ToArray();
            return new X509Certificate2(bytes, (string)null, X509KeyStorageFlags.PersistKeySet);
        }
コード例 #13
0
 /// <summary>
 /// Adds entry to the keystore. This method updates the UI
 /// so it shud be called from UI Thread.
 /// </summary>
 /// <param name="alias"></param>
 /// <param name="cert"></param>
 /// <param name="keypair"></param>
 public void AddEntry(String alias, X509Certificate cert, AsymmetricCipherKeyPair keypair)
 {
     if (keypair == null)
     {
         _store.SetCertificateEntry(alias, X509Utils.WrapX509Certificates(cert)[0]);
         _listItems.Add(new ListItemEntry(KeyStoreEntryType.TrustCertEntry, alias, cert));
     }
     else
     {
         _store.SetKeyEntry(alias, new AsymmetricKeyEntry(keypair.Private), X509Utils.WrapX509Certificates(cert));
         _listItems.Add(new ListItemEntry(KeyStoreEntryType.KeyPairEntry, alias, cert));
     }
     if (!ReadOnlyKeyStore)
     {
         //signal that it has been changed
         Changed = true;
         Save();
     }
 }
コード例 #14
0
ファイル: SSCertGenerator.cs プロジェクト: zhouzu/smtp4dev
        public static System.Security.Cryptography.X509Certificates.X509Certificate2 CreateSelfSignedCertificate(string hostname)
        {
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom             random          = new SecureRandom(randomGenerator);

            X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator();

            certGenerator.SetSubjectDN(new X509Name("CN=" + hostname));
            certGenerator.SetIssuerDN(new X509Name("CN=" + hostname));

            BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            certGenerator.SetSerialNumber(serialNumber);
            certGenerator.SetSignatureAlgorithm("SHA256WithRSA");

            certGenerator.SetNotBefore(DateTime.UtcNow.Date);
            certGenerator.SetNotAfter(DateTime.UtcNow.Date.AddYears(10));

            KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, 2048);

            RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            AsymmetricCipherKeyPair keypair = keyPairGenerator.GenerateKeyPair();

            certGenerator.SetPublicKey(keypair.Public);

            var cert = certGenerator.Generate(keypair.Private, random);


            Pkcs12Store store            = new Pkcs12Store();
            var         certificateEntry = new X509CertificateEntry(cert);

            store.SetCertificateEntry("cert", certificateEntry);
            store.SetKeyEntry("cert", new AsymmetricKeyEntry(keypair.Private), new[] { certificateEntry });
            var stream = new MemoryStream();

            store.Save(stream, "".ToCharArray(), random);

            return(new X509Certificate2(
                       stream.ToArray(), "",
                       X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable));
        }
コード例 #15
0
        public X509Certificate2 ConvertBouncyCert(Org.BouncyCastle.X509.X509Certificate BouncyCert, AsymmetricCipherKeyPair KeyPair)
        {
            var pkcs12Store = new Pkcs12Store();
            var certEntry   = new X509CertificateEntry(BouncyCert);

            pkcs12Store.SetCertificateEntry(BouncyCert.SerialNumber.ToString(), certEntry);
            pkcs12Store.SetKeyEntry(BouncyCert.SerialNumber.ToString(),
                                    new AsymmetricKeyEntry(KeyPair.Private), new[] { certEntry });

            X509Certificate2 keyedCert;

            using (MemoryStream pfxStream = new MemoryStream()) {
                pkcs12Store.Save(pfxStream, null, new SecureRandom());
                pfxStream.Seek(0, SeekOrigin.Begin);
                keyedCert = new X509Certificate2(pfxStream.ToArray(), "", X509KeyStorageFlags.Exportable);
            }

            return(keyedCert);
        }
コード例 #16
0
ファイル: CryptoModule.cs プロジェクト: SosnoV/PKRYLast
        public static X509Certificate2 GenerateCeriticate(string subjectName,
                                                          string Pwd      = "bar",
                                                          string FilePath = "cert.pfx",
                                                          string Alias    = "CryptoModule")
        {
            var kpGen = new RsaKeyPairGenerator();

            kpGen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), keyLength));
            var kp = kpGen.GenerateKeyPair();


            var certGenerator = new X509V3CertificateGenerator();
            var certName      = new X509Name("CN=" + subjectName);
            var serialNo      = BigInteger.ProbablePrime(120, new Random());

            certGenerator.SetSerialNumber(serialNo);
            certGenerator.SetSubjectDN(certName);
            certGenerator.SetIssuerDN(certName);
            certGenerator.SetNotAfter(DateTime.Now.AddDays(1));
            certGenerator.SetNotBefore(DateTime.Now);
            certGenerator.SetSignatureAlgorithm("SHA1withRSA");
            certGenerator.SetPublicKey(kp.Public);

            var newCertificate = certGenerator.Generate(kp.Private);

            var store     = new Pkcs12Store();
            var certEntry = new X509CertificateEntry(newCertificate);

            store.SetCertificateEntry(Alias, certEntry);
            store.SetKeyEntry(Alias, new AsymmetricKeyEntry(kp.Private), new[] { certEntry });

            using (var certFile = File.Create(FilePath))
            {
                store.Save(certFile, Pwd.ToCharArray(), new SecureRandom(new CryptoApiRandomGenerator()));
            }

            var X509net = new System.Security.Cryptography.X509Certificates.X509Certificate2(FilePath,
                                                                                             Pwd,
                                                                                             X509KeyStorageFlags.Exportable);

            ImportCert(X509net);
            return(X509net);
        }
コード例 #17
0
        private static X509Certificate2 ConvertToWindows(Org.BouncyCastle.X509.X509Certificate newCert, AsymmetricCipherKeyPair kp)
        {
            var tempStorePwd  = "FlyingGoats4545"; // RandomGenerators.GetRandomString(50, 75);
            var tempStoreFile = new FileInfo(Path.GetTempFileName());

            try
            {
                // store key
                {
                    var newStore = new Pkcs12Store();

                    var certEntry = new X509CertificateEntry(newCert);

                    newStore.SetCertificateEntry(
                        Environment.MachineName,
                        certEntry
                        );

                    newStore.SetKeyEntry(
                        Environment.MachineName,
                        new AsymmetricKeyEntry(kp.Private),
                        new[] { certEntry }
                        );

                    using (var s = tempStoreFile.Create())
                    {
                        newStore.Save(
                            s,
                            tempStorePwd.ToCharArray(),
                            new SecureRandom(new CryptoApiRandomGenerator())
                            );
                    }
                }

                // reload key
                return(new X509Certificate2(tempStoreFile.FullName, tempStorePwd));
            }
            finally
            {
                tempStoreFile.Delete();
            }
        }
コード例 #18
0
        private void ExportToPFX(AsymmetricKeyParameter privateKey, X509Certificate input, string fileName, string password)
        {
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom             random          = new SecureRandom(randomGenerator);
            Pkcs12Store          store            = new Pkcs12Store();
            X509CertificateEntry certificateEntry = new X509CertificateEntry(input);

            string friendlyName = input.SubjectDN.ToString();

            store.SetCertificateEntry(friendlyName, certificateEntry);
            store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(privateKey), new[] { certificateEntry });

            var stream = new MemoryStream();

            // Get the cert
            store.Save(stream, password.ToCharArray(), random);
            File.WriteAllBytes(fileName, stream.ToArray());

            stream.Close();
        }
コード例 #19
0
        private System.Security.Cryptography.X509Certificates.X509Certificate2 ConvertCertificate(AsymmetricKeyParameter privateKey, X509Certificate input, string friendlyName)
        {
            const string password = "******";

            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom             random          = new SecureRandom(randomGenerator);
            Pkcs12Store          store            = new Pkcs12Store();
            X509CertificateEntry certificateEntry = new X509CertificateEntry(input);

            store.SetCertificateEntry(friendlyName, certificateEntry);
            store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(privateKey), new[] { certificateEntry });

            var stream = new MemoryStream();

            store.Save(stream, password.ToCharArray(), random);
            System.Security.Cryptography.X509Certificates.X509Certificate2 result = new System.Security.Cryptography.X509Certificates.X509Certificate2(stream.ToArray(), password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.PersistKeySet | System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable);
            stream.Close();

            return(result);
        }
コード例 #20
0
        /// <summary>
        /// Convert DER encoded private key data and certificate data into a PKCS12 container.
        /// </summary>
        /// <param name="password">The password to encrypt the container with, or null for no encryption.</param>
        /// <param name="privateKeyData">The private key data that will be stored in the container.</param>
        /// <param name="certificateData">The list of certificates that will be stored in the container.</param>
        /// <returns>A PKCS12 byte array.</returns>
        static public byte[] GetPkcs12Certificate(string password, byte[] privateKeyData, ICollection <byte[]> certificateData)
        {
            var certPrivateKey = PrivateKeyFactory.CreateKey(privateKeyData);
            List <X509CertificateEntry> certificates = new List <X509CertificateEntry>();
            var x509Parser = new X509CertificateParser();
            var pkStore    = new Pkcs12Store();

            //
            // Load all the certificates from the raw data.
            //
            foreach (var certdata in certificateData)
            {
                certificates.Add(new X509CertificateEntry(x509Parser.ReadCertificate(certdata)));
            }

            //
            // Set the primary certificate and key.
            //
            var keyEntry = new AsymmetricKeyEntry(certPrivateKey);

            pkStore.SetCertificateEntry(string.Empty, certificates[0]);
            pkStore.SetKeyEntry(string.Empty, new AsymmetricKeyEntry(certPrivateKey), new[] { certificates[0] });

            //
            // Add in any additional chain certificates.
            //
            for (int i = 1; i < certificates.Count; i++)
            {
                pkStore.SetCertificateEntry(i.ToString(), certificates[i]);
            }

            //
            // Do a final conversion of the certificate data into a PKCS12 blob and add it to the store.
            //
            using (var ms = new MemoryStream())
            {
                pkStore.Save(ms, password?.ToArray(), new SecureRandom());

                return(ms.ToArray());
            }
        }
コード例 #21
0
        public static X509Certificate2 CreateX509Certificate2(AsymmetricCipherKeyPair kp)
        {
            var random = new SecureRandom();
            var sf     = new Asn1SignatureFactory(HashAlg.SHA256withRSA.ToString(), kp.Private, random);

            var gen = new X509V3CertificateGenerator();

            gen.SetSerialNumber(BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random));
            var subject = new X509Name("CN=" + "ebics.org");

            gen.SetSubjectDN(subject);
            gen.SetIssuerDN(subject);
            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = notBefore.AddYears(10);

            gen.SetNotBefore(notBefore);
            gen.SetNotAfter(notAfter);
            gen.SetPublicKey(kp.Public);
            var bouncyCert = gen.Generate(sf);

            var authorityKeyIdentifier = new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public), new GeneralNames(new GeneralName(subject)), bouncyCert.SerialNumber);

            gen.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, false, authorityKeyIdentifier);
            var subjectKeyIdentifier = new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public));

            gen.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, false, subjectKeyIdentifier);
            gen.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(false));

            var store            = new Pkcs12Store();
            var certificateEntry = new X509CertificateEntry(bouncyCert);

            store.SetCertificateEntry(bouncyCert.SubjectDN.ToString(), certificateEntry);
            store.SetKeyEntry(bouncyCert.SubjectDN.ToString(), new AsymmetricKeyEntry(kp.Private), new[] { certificateEntry });
            const string pwd    = "password";
            var          stream = new MemoryStream();

            store.Save(stream, pwd.ToCharArray(), random);
            var msCert = new X509Certificate2(stream.ToArray(), pwd, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

            return(msCert);
        }
コード例 #22
0
        public static byte[] GenerateRootCertificate(string certName, string Password, out byte[] PlainCer)
        {
            PlainCer = null;

            X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();

            X509Name CN = new X509Name("CN=" + certName);

            RsaKeyPairGenerator keypairgen = new RsaKeyPairGenerator();

            keypairgen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 2048));

            AsymmetricCipherKeyPair keypair = keypairgen.GenerateKeyPair();

            certGen.SetSerialNumber(BigInteger.ProbablePrime(120, new Random()));
            certGen.SetIssuerDN(CN);
            certGen.SetNotAfter(new DateTime(2099, 1, 1));
            certGen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0)));
            certGen.SetSubjectDN(CN);
            certGen.SetPublicKey(keypair.Public);

            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom             random          = new SecureRandom(randomGenerator);

            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", keypair.Private, random);

            Org.BouncyCastle.X509.X509Certificate newCert = certGen.Generate(signatureFactory);

            Pkcs12Store pkcs = new Pkcs12Store();

            pkcs.SetCertificateEntry(certName, new X509CertificateEntry(newCert));
            AsymmetricKeyEntry keyentry = new AsymmetricKeyEntry(keypair.Private);

            pkcs.SetKeyEntry(certName, keyentry, new[] { new X509CertificateEntry(newCert) });
            MemoryStream mem = new MemoryStream();

            pkcs.Save(mem, Password.ToCharArray(), random);
            PlainCer = newCert.GetEncoded();

            return(mem.GetBuffer());
        }
コード例 #23
0
        public X509Certificate2 MakeCertificate(string password,
                                                string issuedToDomainName,
                                                string friendlyName,
                                                int validDays)
        {
            _certificateGenerator.Reset();
            _certificateGenerator.SetSignatureAlgorithm(SignatureAlgorithm);
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), _random);

            _certificateGenerator.SetSerialNumber(serialNumber);

            _certificateGenerator.SetSubjectDN(new X509Name(issuedToDomainName));
            _certificateGenerator.SetIssuerDN(_issuer);

            var utcNow = DateTime.UtcNow.AddDays(-1);

            _certificateGenerator.SetNotBefore(utcNow);
            _certificateGenerator.SetNotAfter(utcNow.AddDays(validDays));
            var keyGenerationParameters = new KeyGenerationParameters(_random, _strength);

            var keyPairGenerator = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            _certificateGenerator.SetPublicKey(subjectKeyPair.Public);
            var issuerKeyPair = subjectKeyPair;
            var certificate   = _certificateGenerator.Generate(issuerKeyPair.Private, _random);

            var store            = new Pkcs12Store();
            var certificateEntry = new X509CertificateEntry(certificate);

            store.SetCertificateEntry(friendlyName, certificateEntry);
            store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(subjectKeyPair.Private), new[] { certificateEntry });

            using (var stream = new MemoryStream())
            {
                store.Save(stream, password.ToCharArray(), _random);
                return(new X509Certificate2(stream.ToArray(), password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable));
            }
        }
コード例 #24
0
        static byte[] AsByteArray(X509Certificate certificate, AsymmetricCipherKeyPair key,
                                  string password, SecureRandom random)
        {
            string friendlyName = certificate.SubjectDN.ToString();

            var certificateEntry = new X509CertificateEntry(certificate);

            var store = new Pkcs12Store();

            store.SetCertificateEntry(friendlyName, certificateEntry);

            store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(key.Private), new[] { certificateEntry });

            var stream = new MemoryStream();

            store.Save(stream, password.ToCharArray(), random);

            stream.Position = 0;

            return(stream.ToArray());
        }
コード例 #25
0
 /// <summary>
 /// Includes primary key
 /// </summary>
 /// <param name="cert"></param>
 /// <returns></returns>
 public static byte[] ExportToPkcs12(X509Certificate2 cert)
 {
     try
     {
         var pkcs12Store = new Pkcs12Store();
         var certEntry   = new X509CertificateEntry(DotNetUtilities.FromX509Certificate(cert));
         pkcs12Store.SetCertificateEntry(cert.SubjectName.Name, certEntry);
         pkcs12Store.SetKeyEntry(cert.SubjectName.Name, new AsymmetricKeyEntry(DotNetUtilities.GetKeyPair(cert.PrivateKey).Private), new[] { certEntry });
         using (MemoryStream pfxStream = new MemoryStream())
         {
             pkcs12Store.Save(pfxStream, new char[0], new SecureRandom());
             pfxStream.Seek(0, SeekOrigin.Begin);
             return(pfxStream.ToArray());
         }
     }
     catch
     {
         throw;
         //return cert.Export(X509ContentType.Pkcs12, String.Empty);
     }
 }
        public static X509Certificate2 ReadCertificate(string crtFilePath, string keyFilePath)
        {
            X509Certificate2 cert = new X509Certificate2(crtFilePath, "",
                                                         X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);

            AsymmetricKeyParameter keyParam = ImportPrivateKey(keyFilePath);
            var    store        = new Pkcs12Store();
            string friendlyName = cert.Subject.ToString();
            var    entry        = new X509CertificateEntry(Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(cert));

            store.SetCertificateEntry(friendlyName, entry);
            store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(keyParam), new[] { entry });

            var stream = new MemoryStream();

            store.Save(stream, "".ToArray(), new SecureRandom());

            var convertedCertificate = new X509Certificate2(stream.ToArray(), "", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

            return(convertedCertificate);
        }
コード例 #27
0
        /// <summary>
        /// Exports the specified stream and password to a pkcs12 encrypted file.
        /// </summary>
        /// <remarks>
        /// Exports the specified stream and password to a pkcs12 encrypted file.
        /// </remarks>
        /// <param name="stream">The output stream.</param>
        /// <param name="password">The password to use to lock the private keys.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <para><paramref name="stream"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="password"/> is <c>null</c>.</para>
        /// </exception>
        /// <exception cref="System.IO.IOException">
        /// An error occurred while writing to the stream.
        /// </exception>
        public void Export(Stream stream, string password)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            if (password == null)
            {
                throw new ArgumentNullException("password");
            }

            var store = new Pkcs12Store();

            foreach (var certificate in certs)
            {
                if (keys.ContainsKey(certificate))
                {
                    continue;
                }

                var entry = new X509CertificateEntry(certificate);
                var alias = certificate.GetCommonName();
                store.SetCertificateEntry(alias, entry);
            }

            foreach (var kvp in keys)
            {
                var entry = new AsymmetricKeyEntry(kvp.Value);
                var cert  = new X509CertificateEntry(kvp.Key);
                var chain = new List <X509CertificateEntry> ();
                var alias = kvp.Key.GetCommonName();

                chain.Add(cert);

                store.SetKeyEntry(alias, entry, chain.ToArray());
            }

            store.Save(stream, password.ToCharArray(), new SecureRandom());
        }
コード例 #28
0
        public static void NewCertificate(byte[] certificateData)
        {
            //var cert = (Org.BouncyCastle.X509.X509Certificate)new Org.BouncyCastle.OpenSsl.PemReader(new StringReader(Encoding.UTF8.GetString(certificateData))).ReadObject();


            var store = new Pkcs12Store(new MemoryStream(certificateData), "".ToCharArray());
            //var certificateEntry = new X509CertificateEntry(cert);
            string friendlyName       = store.Aliases.Cast <string>().First();
            X509CertificateEntry cert = store.GetCertificate(friendlyName);

            store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(privateKey), new[] { cert });

            var stream = new MemoryStream();

            store.Save(stream, password.ToCharArray(), random);

            Certificate = new X509Certificate2(stream.ToArray(), password, X509KeyStorageFlags.Exportable);
            byte[] data = Certificate.Export(X509ContentType.Pfx, password);
            File.WriteAllBytes(Config.AppSettings["CertFile"].Value, data);

            Certificate = new X509Certificate2(Config.AppSettings["CertFile"].Value, password);
        }
コード例 #29
0
        public static X509Certificate2 CreateX509Certificate2()
        {
            // generate new key pair
            var keypairgen = new RsaKeyPairGenerator();

            keypairgen.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
            var keypair = keypairgen.GenerateKeyPair();

            // generate x509
            var signatureFactory = new Asn1SignatureFactory("SHA256WithRSA", keypair.Private, new SecureRandom());
            var generator        = new X509V3CertificateGenerator();
            var commonName       = new X509Name("CN=test");
            var serialNumber     = BigInteger.ProbablePrime(120, new SecureRandom());

            generator.SetSerialNumber(serialNumber);
            generator.SetSubjectDN(commonName);
            generator.SetIssuerDN(commonName);
            generator.SetNotAfter(DateTime.UtcNow.AddYears(99));
            generator.SetNotBefore(DateTime.UtcNow);
            generator.SetPublicKey(keypair.Public);

            var bouncyCert = generator.Generate(signatureFactory);

            // convert to .NET certificate
            var store            = new Pkcs12Store();
            var alias            = bouncyCert.SubjectDN.ToString();
            var certificateEntry = new X509CertificateEntry(bouncyCert);

            store.SetCertificateEntry(alias, certificateEntry);
            store.SetKeyEntry(alias, new AsymmetricKeyEntry(keypair.Private), new[] { certificateEntry });

            var          stream   = new MemoryStream();
            const string password = "******";

            store.Save(stream, password.ToCharArray(), new SecureRandom());
            return(new X509Certificate2(stream.ToArray(), password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable));
        }
コード例 #30
0
 /// <summary>
 /// Create a Pfx blob with a private key by combining
 /// a bouncy castle X509Certificate and a private key.
 /// </summary>
 internal static byte[] CreatePfxWithPrivateKey(
     Org.BouncyCastle.X509.X509Certificate certificate,
     string friendlyName,
     AsymmetricKeyParameter privateKey,
     string passcode,
     SecureRandom random)
 {
     // create pkcs12 store for cert and private key
     using (MemoryStream pfxData = new MemoryStream())
     {
         Pkcs12StoreBuilder builder = new Pkcs12StoreBuilder();
         builder.SetUseDerEncoding(true);
         Pkcs12Store            pkcsStore = builder.Build();
         X509CertificateEntry[] chain     = new X509CertificateEntry[1];
         chain[0] = new X509CertificateEntry(certificate);
         if (string.IsNullOrEmpty(friendlyName))
         {
             friendlyName = GetCertificateCommonName(certificate);
         }
         pkcsStore.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(privateKey), chain);
         pkcsStore.Save(pfxData, passcode.ToCharArray(), random);
         return(pfxData.ToArray());
     }
 }