Exemple #1
0
        /// <summary>
        /// Builds the PFX with specified friendly name.
        /// </summary>
        /// <param name="friendlyName">The friendly name.</param>
        /// <param name="password">The password.</param>
        /// <returns>The PFX data.</returns>
        public byte[] Build(string friendlyName, string password)
        {
            var keyPair = LoadKeyPair();
            var store   = new Pkcs12StoreBuilder().Build();

            var entry = new X509CertificateEntry(certificate);

            store.SetCertificateEntry(friendlyName, entry);

            if (FullChain && !certificate.IssuerDN.Equivalent(certificate.SubjectDN))
            {
                var certChain        = FindIssuers();
                var certChainEntries = certChain.Select(c => new X509CertificateEntry(c)).ToList();
                certChainEntries.Add(entry);

                store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(keyPair.Private), certChainEntries.ToArray());
            }
            else
            {
                store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(keyPair.Private), new[] { entry });
            }

            using (var buffer = new MemoryStream())
            {
                store.Save(buffer, password.ToCharArray(), new SecureRandom());
                return(buffer.ToArray());
            }
        }
Exemple #2
0
        private static void Teste(AsymmetricCipherKeyPair keys)
        {
            string certSubjectName = "UShadow_RSA";
            var    certName        = new X509Name("CN=" + certSubjectName);
            var    serialNo        = Org.BouncyCastle.Math.BigInteger.ProbablePrime(120, new Random());


            X509V3CertificateGenerator gen2 = new X509V3CertificateGenerator();

            gen2.SetSerialNumber(serialNo);
            gen2.SetSubjectDN(certName);
            gen2.SetIssuerDN(new X509Name(true, "CN=UShadow"));
            gen2.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(30, 0, 0, 0)));
            gen2.SetNotAfter(DateTime.Now.AddYears(2));
            gen2.SetSignatureAlgorithm("sha256WithRSA");

            gen2.SetPublicKey(keys.Public);

            Org.BouncyCastle.X509.X509Certificate newCert = gen2.Generate(keys.Private);

            Pkcs12Store store = new Pkcs12StoreBuilder().Build();

            X509CertificateEntry certEntry = new X509CertificateEntry(newCert);

            store.SetCertificateEntry(newCert.SubjectDN.ToString(), certEntry);

            AsymmetricKeyEntry keyEntry = new AsymmetricKeyEntry(keys.Private);

            store.SetKeyEntry(newCert.SubjectDN.ToString() + "_key", keyEntry, new X509CertificateEntry[] { certEntry });
        }
        private static void SavePkcs12Certificate(CertificateChainWithPrivateKey certChainWithKey, string?password,
                                                  string certFilePath, bool chain)
        {
            if (File.Exists(certFilePath))
            {
                throw new ArgumentException("Cert file already exists. Please remove it or switch directories.");
            }

            var store = new Pkcs12StoreBuilder().Build();

            // cert chain
            var chainLen = 1;

            if (chain)
            {
                chainLen = certChainWithKey.Certificates.Length;
            }

            for (var i = 0; i < chainLen; i++)
            {
                var cert      = certChainWithKey.Certificates[i];
                var certEntry = new X509CertificateEntry(cert);
                store.SetCertificateEntry(cert.SubjectDN.ToString(), certEntry);
            }

            // private key
            var primaryCert = certChainWithKey.PrimaryCertificate;
            var keyEntry    = new AsymmetricKeyEntry(certChainWithKey.PrivateKey);

            store.SetKeyEntry(primaryCert.SubjectDN.ToString(), keyEntry,
                              new[] { new X509CertificateEntry(primaryCert) });

            using var stream = File.OpenWrite(certFilePath);
            store.Save(stream, password?.ToCharArray(), new SecureRandom());
        }
        public static X509Certificate2 CreateSelfSignedClientCertificate(string commonNameValue, RavenServer.CertificateHolder certificateHolder, out byte[] certBytes)
        {
            var serverCertBytes = certificateHolder.Certificate.Export(X509ContentType.Cert);
            var readCertificate = new X509CertificateParser().ReadCertificate(serverCertBytes);

            CreateSelfSignedCertificateBasedOnPrivateKey(
                commonNameValue,
                readCertificate.SubjectDN,
                (certificateHolder.PrivateKey.Key, readCertificate.GetPublicKey()),
                true,
                false,
                5,
                out certBytes);


            ValidateNoPrivateKeyInServerCert(serverCertBytes);

            Pkcs12Store store      = new Pkcs12StoreBuilder().Build();
            var         serverCert = DotNetUtilities.FromX509Certificate(certificateHolder.Certificate);

            store.Load(new MemoryStream(certBytes), Array.Empty <char>());
            store.SetCertificateEntry(serverCert.SubjectDN.ToString(), new X509CertificateEntry(serverCert));

            var memoryStream = new MemoryStream();

            store.Save(memoryStream, Array.Empty <char>(), GetSeededSecureRandom());
            certBytes = memoryStream.ToArray();

            var cert = new X509Certificate2(certBytes, (string)null, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);

            return(cert);
        }
        public static void CreatePfxFile(
            IReadOnlyList <X509Certificate> certChain,
            AsymmetricKeyParameter privateKey,
            string unsecurePassword,
            Stream output)
        {
            new { certChain }.Must().NotBeNullNorEmptyEnumerableNorContainAnyNulls();
            new { privateKey }.Must().NotBeNull();
            new { privateKey.IsPrivate }.Must().BeTrue();
            new { unsecurePassword }.Must().NotBeNullNorWhiteSpace();
            new { output }.Must().NotBeNull();
            new { output.CanWrite }.Must().BeTrue();

            certChain = certChain.OrderCertChainFromLowestToHighestLevelOfTrust();

            var store       = new Pkcs12StoreBuilder().Build();
            var certEntries = new List <X509CertificateEntry>();

            foreach (var cert in certChain)
            {
                var certEntry = new X509CertificateEntry(cert);
                certEntries.Add(certEntry);
                var certSubjectAttributes = cert.GetX509SubjectAttributes();
                var certStoreKey          = certSubjectAttributes[X509SubjectAttributeKind.CommonName];
                store.SetCertificateEntry(certStoreKey, certEntry);
            }

            var keyEntry  = new AsymmetricKeyEntry(privateKey);
            var firstCert = certChain.First();
            var firstCertSubjectAttributes = firstCert.GetX509SubjectAttributes();

            store.SetKeyEntry(firstCertSubjectAttributes[X509SubjectAttributeKind.CommonName], keyEntry, certEntries.ToArray());
            store.Save(output, unsecurePassword.ToCharArray(), new SecureRandom());
        }
Exemple #6
0
 /// <summary>
 /// Generate Pkcs#12 certificate.
 /// </summary>
 /// <param name="privateKey">Asymmetric private key.</param>
 /// <param name="privateKeyAlias">The alias of private key.</param>
 /// <param name="namedCerts">Certificate collection with alias set.</param>
 /// <param name="password">Password.</param>
 /// <returns></returns>
 /// <exception cref="Exception"/>
 public static Pkcs12Store GeneratePkcs12(AsymmetricKeyParameter privateKey,
                                          string privateKeyAlias,
                                          Dictionary <string, X509Certificate> namedCerts,
                                          string password)
 {
     if (privateKey is null)
     {
         throw new ArgumentNullException(nameof(privateKey));
     }
     if (privateKeyAlias is null)
     {
         throw new ArgumentNullException(nameof(privateKeyAlias));
     }
     if (namedCerts is null)
     {
         throw new ArgumentNullException(nameof(namedCerts));
     }
     using (MemoryStream ms = new MemoryStream())
     {
         Pkcs12Store store = new Pkcs12StoreBuilder().Build();
         List <X509CertificateEntry> certEntries = new List <X509CertificateEntry>();
         foreach (KeyValuePair <string, X509Certificate> namedCert in namedCerts)
         {
             X509CertificateEntry certEntry = new X509CertificateEntry(namedCert.Value);
             store.SetCertificateEntry(namedCert.Key, certEntry);
             certEntries.Add(certEntry);
         }
         store.SetKeyEntry(privateKeyAlias, new AsymmetricKeyEntry(privateKey), certEntries.ToArray());
         char[] pass = string.IsNullOrWhiteSpace(password) ? null : password.ToCharArray();
         store.Save(ms, pass, Common.ThreadSecureRandom.Value);
         ms.Flush();
         return(new Pkcs12Store(ms, pass));
     }
 }
        public static void GenerateCertificate(GenerateCertificateOptions options)
        {
            //generate random numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            var keyGenerator = GeneratorUtilities.GetKeyPairGenerator(options.Algorithm);

            keyGenerator.Init(new KeyGenerationParameters(new SecureRandom(), options.KeyStrength));

            var keyPair = keyGenerator.GenerateKeyPair();

            //the certificate generator
            var certificateGenerator = new X509V3CertificateGenerator();

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

            //serial number
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            certificateGenerator.SetIssuerDN(options.Issuer);
            certificateGenerator.SetSubjectDN(options.Subject);

            //valid For
            certificateGenerator.SetNotBefore(options.NotBefore);
            certificateGenerator.SetNotAfter(options.NotAfter);

            certificateGenerator.SetPublicKey(keyPair.Public);

            ISignatureFactory signatureFactory = new Asn1SignatureFactory(options.SignatureAlgorithm, keyPair.Private);

            //certificate
            var certificate = certificateGenerator.Generate(signatureFactory);

            certificate.CheckValidity();        //检查当前日期是否在证书的有效期内
            certificate.Verify(keyPair.Public); //使用公钥验证证书的签名

            var certEntry = new X509CertificateEntry(certificate);
            var store     = new Pkcs12StoreBuilder().Build();

            store.SetCertificateEntry(options.FriendlyName, certEntry);   //设置证书
            var chain = new X509CertificateEntry[1];

            chain[0] = certEntry;
            store.SetKeyEntry(options.FriendlyName, new AsymmetricKeyEntry(keyPair.Private), chain);   //设置私钥
            using (var fs = File.Create(options.Path))
            {
                store.Save(fs, options.Password.ToCharArray(), new SecureRandom()); //保存
            }
        }
Exemple #8
0
        private static byte[] GeneratePkcs12(
            Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keys,
            Org.BouncyCastle.X509.X509Certificate cert,
            string friendlyName,
            string password,
            System.Collections.Generic.Dictionary <string, Org.BouncyCastle.X509.X509Certificate> chain)
        {
            System.Collections.Generic.List <X509CertificateEntry> chainCerts =
                new System.Collections.Generic.List <X509CertificateEntry>();

            // Create the PKCS12 store
            Pkcs12Store store = new Pkcs12StoreBuilder().Build();

            // Add a Certificate entry
            X509CertificateEntry certEntry = new X509CertificateEntry(cert);

            store.SetCertificateEntry(friendlyName, certEntry); // use DN as the Alias.
                                                                //chainCerts.Add(certEntry);

            // Add chain entries
            System.Collections.Generic.List <byte[]> additionalCertsAsBytes =
                new System.Collections.Generic.List <byte[]>();
            if (chain != null && chain.Count > 0)
            {
                foreach (System.Collections.Generic.KeyValuePair <string, X509Certificate> additionalCert in chain)
                {
                    additionalCertsAsBytes.Add(additionalCert.Value.GetEncoded());
                }
            }

            if (chain != null && chain.Count > 0)
            {
                System.Collections.Generic.IEnumerable <X509Certificate> addicionalCertsAsX09Chain =
                    BuildCertificateChainBC(cert.GetEncoded(), additionalCertsAsBytes);

                foreach (X509Certificate addCertAsX09 in addicionalCertsAsX09Chain)
                {
                    chainCerts.Add(new X509CertificateEntry(addCertAsX09));
                }
            }

            // Add a key entry
            AsymmetricKeyEntry keyEntry = new AsymmetricKeyEntry(keys.Private);

            // no chain
            store.SetKeyEntry(friendlyName, keyEntry, new X509CertificateEntry[] { certEntry });

            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
            {
                store.Save(memoryStream, password.ToCharArray(), new Org.BouncyCastle.Security.SecureRandom());
                return(memoryStream.ToArray());
            }
        }
Exemple #9
0
        /// <summary>
        /// Load pem encoded cert file
        /// </summary>
        /// <param name="file">Path to pem encoded cert file</param>
        /// <returns>x509 instance.</returns>
        public static X509Certificate2 LoadPemFileCert(string file)
        {
            var certs = new X509CertificateParser().ReadCertificates(File.OpenRead(file));
            var store = new Pkcs12StoreBuilder().Build();

            foreach (X509Certificate cert in certs)
            {
                store.SetCertificateEntry(Guid.NewGuid().ToString(), new X509CertificateEntry(cert));
            }

            using (var pkcs = new MemoryStream())
            {
                store.Save(pkcs, new char[0], new SecureRandom());
                // TODO not a chain
                return(new X509Certificate2(pkcs.ToArray()));
            }
        }
Exemple #10
0
        public async Task InstallAsync(string certResponse)
        {
            #region Bouncy castle PKCS #12 cert file generation
            var data = Convert.FromBase64String(certResponse);

            var parser = new X509CertificateParser();
            var cert   = parser.ReadCertificate(data);

            Pkcs12Store          store     = new Pkcs12StoreBuilder().Build();
            X509CertificateEntry certEntry = new X509CertificateEntry(cert);
            store.SetCertificateEntry(cert.SubjectDN.ToString(), certEntry); // use DN as the Alias.

            AsymmetricKeyEntry keyEntry = new AsymmetricKeyEntry(_privateKey);
            store.SetKeyEntry(cert.SubjectDN.ToString() + "_key", keyEntry, new X509CertificateEntry[] { certEntry }); //

            string pfx      = string.Empty;
            string password = "";
            using (MemoryStream ms = new MemoryStream())
            {
                store.Save(ms, password.ToCharArray(), _random);

                ms.Position = 0;
                await _storage.SetAsync("accessCert", ms.GetWindowsRuntimeBuffer());

                StreamReader streamReader = new StreamReader(ms);
                // Write to .PFX string
                byte[] arr = ms.ToArray();

                pfx = CryptographicBuffer.EncodeToBase64String(arr.AsBuffer());
            }
            #endregion
            await _storage.SetAsync(StorageKeyNames.PrivateKey, pfx);

            await CertificateEnrollmentManager.ImportPfxDataAsync(pfx, password, ExportOption.NotExportable, KeyProtectionLevel.NoConsent, InstallOptions.None, "MAG_CERT");

            // Store the registered cert subject
            if (cert.SubjectDN != null)
            {
                var valueList = cert.SubjectDN.GetValueList(X509Name.CN);
                if (valueList.Count > 0)
                {
                    await _storage.SetAsync(StorageKeyNames.RegisteredCertSubject, (string)valueList[0]);
                }
            }
        }
Exemple #11
0
        /// <summary>
        /// Erstellung eines PKCS KeyStores
        /// </summary>
        /// <param name="certificate">Zertifikat für welches der KeyStore erstellt werden soll</param>
        /// <param name="keyPair">Schlüsselpaar welches dem KeyStore unterliegt</param>
        /// <param name="antragsteller">Antragsteller des Zertifikates</param>
        /// <param name="caZertifikat">Stammzertifikat falls es sich um dieses Zertifikat um ein Clientzertifikat handeln soll</param>
        /// <returns></returns>
        public static Pkcs12Store CreatePkcs12Store(X509Certificate certificate, AsymmetricCipherKeyPair keyPair, string antragsteller, X509Certificate caZertifikat = null)
        {
            Pkcs12Store pkcsStore = new Pkcs12StoreBuilder().Build();

            X509CertificateEntry certEntry = new X509CertificateEntry(certificate);

            pkcsStore.SetCertificateEntry(antragsteller, certEntry);

            if (caZertifikat != null)
            {
                var chainCerts = new List <X509CertificateEntry>();

                Dictionary <string, Org.BouncyCastle.X509.X509Certificate> chain = new Dictionary <string, Org.BouncyCastle.X509.X509Certificate>();
                string caCn = caZertifikat.SubjectDN.GetValues(X509Name.CN)[0].ToString();
                chain.Add(caCn, caZertifikat);

                var additionalCertsAsBytes = new List <byte[]>();
                if (chain != null && chain.Count > 0)
                {
                    foreach (var additionalCert in chain)
                    {
                        additionalCertsAsBytes.Add(additionalCert.Value.GetEncoded());
                    }
                }

                if (chain != null && chain.Count > 0)
                {
                    var addicionalCertsAsX09Chain = BuildCertificateChainBC(certificate.GetEncoded(), additionalCertsAsBytes);

                    foreach (var addCertAsX09 in addicionalCertsAsX09Chain)
                    {
                        X509Certificate tmpCertificate = (X509Certificate)addCertAsX09;
                        chainCerts.Add(new X509CertificateEntry(tmpCertificate));
                    }
                }
            }

            AsymmetricKeyEntry keyEntry = new AsymmetricKeyEntry(keyPair.Private);

            pkcsStore.SetKeyEntry(antragsteller, keyEntry, new X509CertificateEntry[] { certEntry });

            return(pkcsStore);
        }
Exemple #12
0
        public void LoadPem(string certPath, string keyPath)
        {
            using (StreamReader reader = File.OpenText(certPath))
                certificate = (Org.BouncyCastle.X509.X509Certificate) new Org.BouncyCastle.OpenSsl.PemReader(reader).ReadObject();
            using (StreamReader reader = File.OpenText(keyPath))
                privateKey = (AsymmetricKeyParameter) new Org.BouncyCastle.OpenSsl.PemReader(reader).ReadObject();

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

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


            var random = new SecureRandom(new CryptoApiRandomGenerator());
            var stream = new MemoryStream();

            store.Save(stream, "".ToCharArray(), random);
            X509Certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(stream.ToArray(), "");
        }
Exemple #13
0
        /// <summary>
        /// 根据crt以及RSA私钥生成pfx证书
        /// </summary>
        /// <param name="passWord">证书密码</param>
        /// <param name="x509CertData">crt证书</param>
        /// <param name="privateKey">Rsa私钥</param>
        /// <param name="x509CertChainData">证书链</param>
        /// <param name="alias">默认别名</param>
        /// <returns></returns>
        public static MemoryStream GeneratePFX(string passWord, byte[] x509CertData, byte[] privateKey, byte[] x509CertChainData = null, string alias = "PrimaryCertificate")
        {
            RsaPrivateCrtKeyParameters privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(privateKey);
            var         certEntry = GetX509CertificateEntry(x509CertData);
            Pkcs12Store store     = new Pkcs12StoreBuilder().Build();

            store.SetCertificateEntry(alias, certEntry);
            X509CertificateEntry[] chain = new X509CertificateEntry[1];
            if (x509CertChainData != null)
            {
                chain    = new X509CertificateEntry[2];
                chain[1] = GetX509CertificateEntry(x509CertChainData);
            }
            chain[0] = certEntry;
            store.SetKeyEntry(alias, new AsymmetricKeyEntry(privateKeyParam), chain);   //设置私钥
            var ms = new MemoryStream();

            store.Save(ms, passWord.ToCharArray(), new SecureRandom());
            ms.Position = 0;
            return(ms);
        }
Exemple #14
0
        /// <returns>True if a private key was written, false if just the certificate was written.</returns>
        private bool WritePfx(string certPem, string keyPem, string password, string filePath)
        {
            var cert      = ReadCertificate(certPem);
            var certEntry = new X509CertificateEntry(cert);

            if (certEntry?.Certificate == null)
            {
                throw new ArgumentException("The string given as a PEM representation of the certificate could not be read accordingly.", nameof(certPem));
            }

            AsymmetricKeyParameter privKey = null;

            if (!string.IsNullOrEmpty(keyPem))
            {
                privKey = ReadPrivateKey(keyPem);
                if (privKey == null)
                {
                    throw new ArgumentException("The string given as a PEM representation of the private key could not be read accordingly.", nameof(keyPem));
                }
            }

            var store = new Pkcs12StoreBuilder().Build();

            if (privKey != null)
            {
                var chain = new X509CertificateEntry[] { certEntry };
                store.SetKeyEntry("", new AsymmetricKeyEntry(privKey), chain);
            }
            else
            {
                store.SetCertificateEntry("", certEntry);
            }

            using (var p12file = File.Create(filePath))
            {
                store.Save(p12file, password.ToCharArray(), new SecureRandom());
            }
            return(privKey != null);
        }
Exemple #15
0
        private static void SavePkcs12Certificate(CertificateChainWithPrivateKey certChainWithKey,
                                                  string directory, string nameWithoutExtension, bool chain)
        {
            var certFilePath = Path.Combine(directory, $"{nameWithoutExtension}.pfx");

            Console.WriteLine($"[info] saving cert to {certFilePath}");
            if (File.Exists(certFilePath))
            {
                throw new ConcertoUsageException("Cert file already exists. Please remove it or switch directories.");
            }

            var store = new Pkcs12StoreBuilder().Build();

            // cert chain
            var chainLen = 1;

            if (chain)
            {
                chainLen = certChainWithKey.Certificates.Length;
            }

            for (var i = 0; i < chainLen; i++)
            {
                var cert      = certChainWithKey.Certificates[i];
                var certEntry = new X509CertificateEntry(cert);
                store.SetCertificateEntry(cert.SubjectDN.ToString(), certEntry);
            }

            // private key
            var primaryCert = certChainWithKey.PrimaryCertificate;
            var keyEntry    = new AsymmetricKeyEntry(certChainWithKey.PrivateKey);

            store.SetKeyEntry(primaryCert.SubjectDN.ToString(), keyEntry,
                              new[] { new X509CertificateEntry(primaryCert) });

            using var stream = File.OpenWrite(certFilePath);
            store.Save(stream, null, new SecureRandom());
        }
Exemple #16
0
        static bool Gen(string summoner, string region, string password, string file)
        {
            try
            {
                //Later in your Code

                //Requested Certificate Name
                X509Name name = new X509Name("CN=" + summoner + " - " + region + ", OU=Ghostblade Replays, O=Arsslensoft");

                //Key generation 2048bits
                RsaKeyPairGenerator rkpg = new RsaKeyPairGenerator();
                rkpg.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
                AsymmetricCipherKeyPair ackp   = rkpg.GenerateKeyPair();
                X509Certificate2        caCert = new X509Certificate2(GBReplay.Properties.Resources.GBSGN, "KGPAQW7894Q129D7Q1456W9A47897a9s7r5d6");
                //PKCS #10 Certificate Signing Request
                Pkcs10CertificationRequest csr = new Pkcs10CertificationRequest("SHA256WITHRSA", name, ackp.Public, null, ackp.Private);


                AsymmetricKeyParameter publicKey = csr.GetPublicKey();

                // Build a Version1 (No Extensions) Certificate
                DateTime   startDate    = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
                DateTime   expiryDate   = startDate.AddYears(5);
                BigInteger serialNumber = new BigInteger(32, new Random());


                X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

                X509Name dnName = new X509Name(caCert.Subject);

                certGen.SetSerialNumber(serialNumber);
                certGen.SetIssuerDN(dnName);
                certGen.SetNotBefore(startDate);
                certGen.SetNotAfter(expiryDate);
                certGen.SetSubjectDN(name);
                certGen.SetSignatureAlgorithm("SHA256WITHRSA");
                certGen.SetPublicKey(publicKey);

                UserNotice          unotice    = new UserNotice(null, "This certificate must be only used with Ghostblade replays files. This certificate is a property of Arsslensoft any usage of its content without prior request is prohibited.");
                PolicyQualifierInfo pqiunotice = new PolicyQualifierInfo(PolicyQualifierID.IdQtUnotice, unotice);
                PolicyInformation   p          = new PolicyInformation(new DerObjectIdentifier("1.3.6.1.4.1.44215.1.3"), new DerSequence(new PolicyQualifierInfo[1] {
                    pqiunotice
                }));
                certGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
                certGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(DotNetUtilities.FromX509Certificate(caCert).GetPublicKey()));
                certGen.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(publicKey));
                certGen.AddExtension(X509Extensions.KeyUsage, false, new  KeyUsage(KeyUsage.DigitalSignature));
                certGen.AddExtension(X509Extensions.ExtendedKeyUsage, false, new  ExtendedKeyUsage(new KeyPurposeID[] { KeyPurposeID.IdKPCodeSigning }));

                certGen.AddExtension(X509Extensions.CertificatePolicies, false, new DerSequence(p));



                Pkcs12Store pfx   = new Pkcs12Store(new MemoryStream(GBReplay.Properties.Resources.GBSGN), "KGPAQW7894Q129D7Q1456W9A47897a9s7r5d6".ToCharArray());
                string      alias = null;
                foreach (string al in pfx.Aliases)
                {
                    if (pfx.IsKeyEntry(al) && pfx.GetKey(al).Key.IsPrivate)
                    {
                        alias = al;
                        break;
                    }
                }

                //get our Private Key to Sign with

                //   AsymmetricCipherKeyPair caPair = DotNetUtilities.GetKeyPair(caCert.PrivateKey);
                AsymmetricKeyParameter caPair = pfx.GetKey(alias).Key;

                Al.Security.X509.X509Certificate cert = certGen.Generate(caPair);

                Pkcs12Store pk = new Pkcs12StoreBuilder().Build();
                // Add a Certificate entry
                X509CertificateEntry certEntry = new X509CertificateEntry(cert);
                pk.SetCertificateEntry(cert.SubjectDN.ToString(), certEntry); // use DN as the Alias.

                AsymmetricKeyEntry keyEntry = new AsymmetricKeyEntry(ackp.Private);
                pk.SetKeyEntry(cert.SubjectDN.ToString(), keyEntry, new X509CertificateEntry[] { certEntry }); // Note that we only have 1 cert in the 'chain'

                using (var filestream = new FileStream(file, FileMode.Create, FileAccess.ReadWrite))
                    pk.Save(filestream, password.ToCharArray(), new SecureRandom());

                X509Certificate2 cer = new X509Certificate2(File.ReadAllBytes(file), password);
                cer.Verify();
            }
            catch
            {
                return(false);
            }
            return(true);
        }
Exemple #17
0
        /// <summary>
        /// Generate PFX File
        /// </summary>
        /// <param name="signedCERFile"></param>
        /// <param name="privateKeyFile"></param>
        /// <param name="v"></param>
        /// <param name="password"></param>
        private async void GeneratePFXFile(string signedCERFile, string privateKeyFile, string generateCertificateFile,
                                           string password, string friendlyName, string signedCACERFile = null)
        {
            // Prepare the pkcs12 certificate store
            Pkcs12Store            store      = new Pkcs12StoreBuilder().Build();
            AsymmetricKeyParameter privateKey = ReadPrivateKey(privateKeyFile);

            X509CertificateEntry[] chain = null;

            // Check if CA root public key file exist? If exist read data from file and verify certificate inside signed requested public key file with CA root public key
            // If Ca root public key file does not exist, certificate inside signed requested public key file CAN NOT be veryfied
            // Bundle together the private key, signed certificate and CA
            Org.BouncyCastle.X509.X509Certificate CAX509Cert = null;
            if (String.IsNullOrEmpty(signedCACERFile))
            {
                chain = new X509CertificateEntry[1];
                //chain[0] = certEntry;
            }
            else
            {
                chain = new X509CertificateEntry[2];
                //chain[0] = certEntry;

                try
                {
                    // Import the CA certificate
                    X509Certificate2 certCA = new X509Certificate2(signedCACERFile);
                    //then export it like so
                    byte[] p12CA = certCA.Export(X509ContentType.Cert);
                    CAX509Cert = new X509CertificateParser().ReadCertificate(p12CA);
                    X509CertificateEntry certCAEntry = new X509CertificateEntry(CAX509Cert);
                    chain[1] = certCAEntry;
                }
                catch (Exception ex)
                {
                    Brush bckForeground = tbOutputMessageBox.Foreground;
                    tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                    tbOutputMessageBox.Text      += "Error reading root CA certificate file: " + signedCACERFile + "\n";
                    tbOutputMessageBox.Foreground = bckForeground;
                    return;
                }
            }

            // Import data from the signed requested certificate file => file with .cer extension (NOT CA root public key file)
            X509Certificate2 certSigned = new X509Certificate2(signedCERFile);

            int errorNum = 0;

            #region check - old
            // This is .cer public key file and it doesn't have private key => it's OK
            //bool isHasPrivateKey = certSigned.HasPrivateKey;
            //if (!isHasPrivateKey)
            //{
            //    errorNum++;
            //    Brush bckForeground = tbOutputMessageBox.Foreground;
            //    tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
            //    tbOutputMessageBox.Text += "Error, certificate file: "+ signedCERFile+" DOES NOT have a private key!!!" + "\n";
            //    tbOutputMessageBox.Foreground = bckForeground;
            //}

            // This is certificate signed with CA root that not yet been imported to Trusted Root Certification Authorities and can't be verified
            //bool isOK = certSigned.Verify();
            //if (!isOK)
            //{
            //    errorNum++;
            //    Brush bckForeground = tbOutputMessageBox.Foreground;
            //    tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
            //    tbOutputMessageBox.Text += "Error, certificate file: " + signedCERFile + " NOT valid!!!" + "\n";
            //    tbOutputMessageBox.Foreground = bckForeground;
            //}
            #endregion

            //then export it like so
            byte[] p12 = certSigned.Export(X509ContentType.Cert);
            Org.BouncyCastle.X509.X509Certificate signedX509Cert = new X509CertificateParser().ReadCertificate(p12);

            if (CAX509Cert != null)
            {
                try
                {
                    signedX509Cert.Verify(CAX509Cert.GetPublicKey());
                }
                catch (Exception ex)
                {
                    errorNum++;
                    Brush bckForeground = tbOutputMessageBox.Foreground;
                    tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                    tbOutputMessageBox.Text      += "Error certificate file: " + signedCERFile + " Verification error: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n";
                    tbOutputMessageBox.Foreground = bckForeground;
                }
            }
            else
            {
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Yellow);
                tbOutputMessageBox.Text      += "Certificate file: " + signedCERFile + " CAN NOT be verified, because CA root public key file not provided" + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }
            if (errorNum > 0)
            {
                return;
            }

            X509CertificateEntry certEntry = new X509CertificateEntry(signedX509Cert);
            chain[0] = certEntry;
            store.SetKeyEntry(signedX509Cert.SubjectDN.ToString() + "_key", new AsymmetricKeyEntry(privateKey), chain);

            // Add the certificate.
            X509CertificateEntry certificateEntry = new X509CertificateEntry(signedX509Cert);
            store.SetCertificateEntry(friendlyName, certificateEntry);

            // Add the private key.
            store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(privateKey), new[] { certificateEntry });

            try
            {
                using (var filestream = new FileStream(generateCertificateFile, FileMode.Create, FileAccess.ReadWrite))
                {
                    store.Save(filestream, password.ToCharArray(), new SecureRandom());
                }

                if (chain.Length > 1)
                {
                    tbOutputMessageBox.Text += "Certificate file with private key: " + generateCertificateFile + " and CA public key sucessfully generated." + "\n";
                }
                else
                {
                    tbOutputMessageBox.Text += "Certificate file with private key: " + generateCertificateFile + " sucessfully generated." + "\n";
                }
            }
            catch (Exception ex)
            {
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                if (chain.Length > 1)
                {
                    tbOutputMessageBox.Text += "Error, certificate file with private key: " + generateCertificateFile + " and CA public key DOES NOT sucessfully generated." + "\n";
                }
                else
                {
                    tbOutputMessageBox.Text += "Certificate file with private key: " + generateCertificateFile + " DOES NOT sucessfully generated." + "\n";
                }
                tbOutputMessageBox.Foreground = bckForeground;

                var metroWindow = (Application.Current.MainWindow as MetroWindow);
                await metroWindow.ShowMessageAsync("Info Warning",
                                                   "ERROR creating certificate file with private key file (.pfx)" + "\n" +
                                                   "Error: " + ex.Source + " " + ex.Message,
                                                   MessageDialogStyle.Affirmative);

                return;
            }
        }
Exemple #18
0
        public void doTestPkcs12Store()
        {
            BigInteger mod = new BigInteger("bb1be8074e4787a8d77967f1575ef72dd7582f9b3347724413c021beafad8f32dba5168e280cbf284df722283dad2fd4abc750e3d6487c2942064e2d8d80641aa5866d1f6f1f83eec26b9b46fecb3b1c9856a303148a5cc899c642fb16f3d9d72f52526c751dc81622c420c82e2cfda70fe8d13f16cc7d6a613a5b2a2b5894d1", 16);

            MemoryStream stream = new MemoryStream(pkcs12, false);
            Pkcs12Store  store  = new Pkcs12StoreBuilder().Build();

            store.Load(stream, passwd);

            string pName = null;

            foreach (string n in store.Aliases)
            {
                if (store.IsKeyEntry(n))
                {
                    pName = n;
                    //break;
                }
            }

            AsymmetricKeyEntry key = store.GetKey(pName);

            if (!((RsaKeyParameters)key.Key).Modulus.Equals(mod))
            {
                Fail("Modulus doesn't match.");
            }

            X509CertificateEntry[] ch = store.GetCertificateChain(pName);

            if (ch.Length != 3)
            {
                Fail("chain was wrong length");
            }

            if (!ch[0].Certificate.SerialNumber.Equals(new BigInteger("96153094170511488342715101755496684211")))
            {
                Fail("chain[0] wrong certificate.");
            }

            if (!ch[1].Certificate.SerialNumber.Equals(new BigInteger("279751514312356623147411505294772931957")))
            {
                Fail("chain[1] wrong certificate.");
            }

            if (!ch[2].Certificate.SerialNumber.Equals(new BigInteger("11341398017")))
            {
                Fail("chain[2] wrong certificate.");
            }

            //
            // save test
            //
            MemoryStream bOut = new MemoryStream();

            store.Save(bOut, passwd, new SecureRandom());

            stream = new MemoryStream(bOut.ToArray(), false);
            store.Load(stream, passwd);

            key = store.GetKey(pName);

            if (!((RsaKeyParameters)key.Key).Modulus.Equals(mod))
            {
                Fail("Modulus doesn't match.");
            }

            store.DeleteEntry(pName);

            if (store.GetKey(pName) != null)
            {
                Fail("Failed deletion test.");
            }

            //
            // cert chain test
            //
            store.SetCertificateEntry("testCert", ch[2]);

            if (store.GetCertificateChain("testCert") != null)
            {
                Fail("Failed null chain test.");
            }

            //
            // UTF 8 single cert test
            //
            stream = new MemoryStream(certUTF, false);
            store.Load(stream, "user".ToCharArray());

            if (store.GetCertificate("37") == null)
            {
                Fail("Failed to find UTF cert.");
            }

            //
            // try for a self generated certificate
            //
            RsaKeyParameters pubKey = new RsaKeyParameters(
                false,
                new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16),
                new BigInteger("11", 16));

            RsaPrivateCrtKeyParameters privKey = new RsaPrivateCrtKeyParameters(
                new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16),
                new BigInteger("11", 16),
                new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16),
                new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16),
                new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16),
                new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16),
                new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16),
                new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16));

            X509CertificateEntry[] chain = new X509CertificateEntry[] {
                CreateCert(pubKey, privKey, "*****@*****.**", "*****@*****.**")
            };

            store = new Pkcs12StoreBuilder().Build();

            store.SetKeyEntry("privateKey", new AsymmetricKeyEntry(privKey), chain);

            if (!store.ContainsAlias("privateKey") || !store.ContainsAlias("PRIVATEKEY"))
            {
                Fail("couldn't find alias privateKey");
            }

            if (store.IsCertificateEntry("privateKey"))
            {
                Fail("key identified as certificate entry");
            }

            if (!store.IsKeyEntry("privateKey") || !store.IsKeyEntry("PRIVATEKEY"))
            {
                Fail("key not identified as key entry");
            }

            if (!"privateKey".Equals(store.GetCertificateAlias(chain[0].Certificate)))
            {
                Fail("Did not return alias for key certificate privateKey");
            }

            MemoryStream store1Stream = new MemoryStream();

            store.Save(store1Stream, passwd, new SecureRandom());
            testNoExtraLocalKeyID(store1Stream.ToArray());

            //
            // no friendly name test
            //
            stream = new MemoryStream(pkcs12noFriendly, false);
            store.Load(stream, noFriendlyPassword);

            pName = null;

            foreach (string n in store.Aliases)
            {
                if (store.IsKeyEntry(n))
                {
                    pName = n;
                    //break;
                }
            }

            ch = store.GetCertificateChain(pName);

            //for (int i = 0; i != ch.Length; i++)
            //{
            //	Console.WriteLine(ch[i]);
            //}

            if (ch.Length != 1)
            {
                Fail("no cert found in pkcs12noFriendly");
            }

            //
            // failure tests
            //
            ch = store.GetCertificateChain("dummy");

            store.GetCertificateChain("DUMMY");

            store.GetCertificate("dummy");

            store.GetCertificate("DUMMY");

            //
            // storage test
            //
            stream = new MemoryStream(pkcs12StorageIssue, false);
            store.Load(stream, storagePassword);

            pName = null;

            foreach (string n in store.Aliases)
            {
                if (store.IsKeyEntry(n))
                {
                    pName = n;
                    //break;
                }
            }

            ch = store.GetCertificateChain(pName);
            if (ch.Length != 2)
            {
                Fail("Certificate chain wrong length");
            }

            store.Save(new MemoryStream(), storagePassword, new SecureRandom());

            //
            // basic certificate check
            //
            store.SetCertificateEntry("cert", ch[1]);

            if (!store.ContainsAlias("cert") || !store.ContainsAlias("CERT"))
            {
                Fail("couldn't find alias cert");
            }

            if (!store.IsCertificateEntry("cert") || !store.IsCertificateEntry("CERT"))
            {
                Fail("cert not identified as certificate entry");
            }

            if (store.IsKeyEntry("cert") || store.IsKeyEntry("CERT"))
            {
                Fail("cert identified as key entry");
            }

            if (!store.IsEntryOfType("cert", typeof(X509CertificateEntry)))
            {
                Fail("cert not identified as X509CertificateEntry");
            }

            if (!store.IsEntryOfType("CERT", typeof(X509CertificateEntry)))
            {
                Fail("CERT not identified as X509CertificateEntry");
            }

            if (store.IsEntryOfType("cert", typeof(AsymmetricKeyEntry)))
            {
                Fail("cert identified as key entry via AsymmetricKeyEntry");
            }

            if (!"cert".Equals(store.GetCertificateAlias(ch[1].Certificate)))
            {
                Fail("Did not return alias for certificate entry");
            }

            //
            // test restoring of a certificate with private key originally as a ca certificate
            //
            store = new Pkcs12StoreBuilder().Build();

            store.SetCertificateEntry("cert", ch[0]);

            if (!store.ContainsAlias("cert") || !store.ContainsAlias("CERT"))
            {
                Fail("restore: couldn't find alias cert");
            }

            if (!store.IsCertificateEntry("cert") || !store.IsCertificateEntry("CERT"))
            {
                Fail("restore: cert not identified as certificate entry");
            }

            if (store.IsKeyEntry("cert") || store.IsKeyEntry("CERT"))
            {
                Fail("restore: cert identified as key entry");
            }

            if (store.IsEntryOfType("cert", typeof(AsymmetricKeyEntry)))
            {
                Fail("restore: cert identified as key entry via AsymmetricKeyEntry");
            }

            if (store.IsEntryOfType("CERT", typeof(AsymmetricKeyEntry)))
            {
                Fail("restore: cert identified as key entry via AsymmetricKeyEntry");
            }

            if (!store.IsEntryOfType("cert", typeof(X509CertificateEntry)))
            {
                Fail("restore: cert not identified as X509CertificateEntry");
            }

            //
            // test of reading incorrect zero-length encoding
            //
            stream = new MemoryStream(pkcs12nopass, false);
            store.Load(stream, "".ToCharArray());
        }
Exemple #19
0
        private void doTestParams(
            byte[]  ecParameterEncoded,
            bool compress)
        {
//			string keyStorePass = "******";
            Asn1Sequence             seq = (Asn1Sequence)Asn1Object.FromByteArray(ecParameterEncoded);
            X9ECParameters           x9  = new X9ECParameters(seq);
            IAsymmetricCipherKeyPair kp  = null;
            bool success = false;

            while (!success)
            {
                IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("ECDSA");
//				kpg.Init(new ECParameterSpec(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed()));
                ECDomainParameters ecParams = new ECDomainParameters(
                    x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed());
                kpg.Init(new ECKeyGenerationParameters(ecParams, new SecureRandom()));
                kp = kpg.GenerateKeyPair();
                // The very old Problem... we need a certificate chain to
                // save a private key...
                ECPublicKeyParameters pubKey = (ECPublicKeyParameters)kp.Public;

                if (!compress)
                {
                    //pubKey.setPointFormat("UNCOMPRESSED");
                    pubKey = SetPublicUncompressed(pubKey, false);
                }

                byte[] x = pubKey.Q.X.ToBigInteger().ToByteArrayUnsigned();
                byte[] y = pubKey.Q.Y.ToBigInteger().ToByteArrayUnsigned();
                if (x.Length == y.Length)
                {
                    success = true;
                }
            }

            // The very old Problem... we need a certificate chain to
            // save a private key...

            X509CertificateEntry[] chain = new X509CertificateEntry[] {
                new X509CertificateEntry(GenerateSelfSignedSoftECCert(kp, compress))
            };

//			KeyStore keyStore = KeyStore.getInstance("BKS");
//			keyStore.load(null, keyStorePass.ToCharArray());
            Pkcs12Store keyStore = new Pkcs12StoreBuilder().Build();

            keyStore.SetCertificateEntry("ECCert", chain[0]);

            ECPrivateKeyParameters privateECKey = (ECPrivateKeyParameters)kp.Private;

            keyStore.SetKeyEntry("ECPrivKey", new AsymmetricKeyEntry(privateECKey), chain);

            // Test ec sign / verify
            ECPublicKeyParameters pub = (ECPublicKeyParameters)kp.Public;

//			string oldPrivateKey = new string(Hex.encode(privateECKey.getEncoded()));
            byte[] oldPrivateKeyBytes = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateECKey).GetDerEncoded();
            string oldPrivateKey      = Hex.ToHexString(oldPrivateKeyBytes);

//			string oldPublicKey = new string(Hex.encode(pub.getEncoded()));
            byte[] oldPublicKeyBytes      = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pub).GetDerEncoded();
            string oldPublicKey           = Hex.ToHexString(oldPublicKeyBytes);
            ECPrivateKeyParameters newKey = (ECPrivateKeyParameters)
                                            keyStore.GetKey("ECPrivKey").Key;
            ECPublicKeyParameters newPubKey = (ECPublicKeyParameters)
                                              keyStore.GetCertificate("ECCert").Certificate.GetPublicKey();

            if (!compress)
            {
                // TODO Private key compression?
                //newKey.setPointFormat("UNCOMPRESSED");
                //newPubKey.setPointFormat("UNCOMPRESSED");
                newPubKey = SetPublicUncompressed(newPubKey, false);
            }

//			string newPrivateKey = new string(Hex.encode(newKey.getEncoded()));
            byte[] newPrivateKeyBytes = PrivateKeyInfoFactory.CreatePrivateKeyInfo(newKey).GetDerEncoded();
            string newPrivateKey      = Hex.ToHexString(newPrivateKeyBytes);

//			string newPublicKey = new string(Hex.encode(newPubKey.getEncoded()));
            byte[] newPublicKeyBytes = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(newPubKey).GetDerEncoded();
            string newPublicKey      = Hex.ToHexString(newPublicKeyBytes);

            if (!oldPrivateKey.Equals(newPrivateKey))
//			if (!privateECKey.Equals(newKey))
            {
                Fail("failed private key comparison");
            }

            if (!oldPublicKey.Equals(newPublicKey))
//			if (!pub.Equals(newPubKey))
            {
                Fail("failed public key comparison");
            }
        }
        /// <summary>
        /// 生成X509 V3证书
        /// </summary>
        /// <param name="certPath">Cert证书路径</param>
        /// <param name="endDate">证书失效时间</param>
        /// <param name="keySize">密钥长度</param>
        /// <param name="password">证书密码</param>
        /// <param name="signatureAlgorithm">设置将用于签署此证书的签名算法</param>
        /// <param name="issuer">设置此证书颁发者的DN</param>
        /// <param name="subject">设置此证书使用者的DN</param>
        /// <param name="pfxPath">Pfx证书路径</param>
        /// <param name="friendlyName">设置证书友好名称(可选)</param>
        /// <param name="startDate">证书生效时间</param>
        /// <param name="algorithm">加密算法</param>
        public static void X509V3(string algorithm, int keySize, string password, string signatureAlgorithm,
                                  DateTime startDate, DateTime endDate, X509Name issuer, X509Name subject, string certPath, string pfxPath,
                                  string friendlyName = "")
        {
            //generate Random Numbers
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom             random          = new SecureRandom(randomGenerator);

            var keyGenerator = GeneratorUtilities.GetKeyPairGenerator(algorithm);

            keyGenerator.Init(new KeyGenerationParameters(new SecureRandom(), keySize));

            var keyPair = keyGenerator.GenerateKeyPair();

            var v3CertGen    = new X509V3CertificateGenerator();
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random);

            v3CertGen.SetSerialNumber(serialNumber);                                                   //设置证书的序列号

            v3CertGen.SetIssuerDN(issuer);                                                             //设置颁发者信息
            v3CertGen.SetSubjectDN(subject);                                                           //设置使用者信息

            v3CertGen.SetNotBefore(startDate);                                                         //设置证书的生效日期
            v3CertGen.SetNotAfter(endDate);                                                            //设置证书失效的日期
            v3CertGen.SetPublicKey(keyPair.Public);                                                    //设置此证书的公钥

            ISignatureFactory sigFact = new Asn1SignatureFactory(signatureAlgorithm, keyPair.Private); //签名算法&设置此证书的私钥

            var spki = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public);

            //设置一些扩展字段
            //基本约束
            v3CertGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
            //使用者密钥标识符
            v3CertGen.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(spki));
            //授权密钥标识符
            v3CertGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(spki));

            var x509Certificate = v3CertGen.Generate(sigFact); //生成证书

            x509Certificate.CheckValidity();                   //检查当前日期是否在证书的有效期内
            x509Certificate.Verify(keyPair.Public);            //使用公钥验证证书的签名

            var certificate2 = new X509Certificate2(DotNetUtilities.ToX509Certificate(x509Certificate))
            {
                FriendlyName = friendlyName, //设置友好名称
            };

            //cer公钥文件
            var bytes = certificate2.Export(X509ContentType.Cert);

            using (var fs = new FileStream(certPath, FileMode.Create))
            {
                fs.Write(bytes, 0, bytes.Length);
            }

            //pfx证书,包含公钥私钥
            //CopyWithPrivateKey netstandard2.1支持
            certificate2 =
                certificate2.CopyWithPrivateKey(DotNetUtilities.ToRSA((RsaPrivateCrtKeyParameters)keyPair.Private));

            var bytes2 = certificate2.Export(X509ContentType.Pfx, password);

            using (var fs = new FileStream(pfxPath, FileMode.Create))
            {
                fs.Write(bytes2, 0, bytes2.Length);
            }


            //如果使用 netstandard2.0 请使用下面的代码
#if NETSTANDARD2_0
            var certEntry = new X509CertificateEntry(x509Certificate);
            var store     = new Pkcs12StoreBuilder().Build();
            store.SetCertificateEntry(friendlyName, certEntry);   //设置证书
            var chain = new X509CertificateEntry[1];
            chain[0] = certEntry;
            store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(keyPair.Private), chain);   //设置私钥
            using (var fs = File.Create(pfxPath))
            {
                store.Save(fs, password.ToCharArray(), new SecureRandom()); //保存
            }
#endif
        }
Exemple #21
0
        //
        // Summary:
        //     /// Method responsible for generate certificate. ///
        //
        // Parameters:
        //   request:
        //     The request param.
        //
        public CreateCertificateResult Generate(CreateCertificateCommand request)
        {
            AsymmetricKeyParameter caPrivateKey = null;

            var caCert = GenerateCACertificate("CN=MyROOTCA", ref caPrivateKey);


            SecureRandom random = new SecureRandom();

            RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator();

            keyPairGenerator.Init(new KeyGenerationParameters(random, 2048));

            AsymmetricCipherKeyPair subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            IDictionary issuerAttrs  = FactoryIssuerAttrs();
            IDictionary subjectAttrs = FactorySubjectAttrs(request);

            BigInteger serialNumber = BigInteger.ProbablePrime(120, new Random());

            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();

            certificateGenerator.SetSerialNumber(serialNumber);
            certificateGenerator.SetIssuerDN(new X509Name(new ArrayList(issuerAttrs.Keys), issuerAttrs));
            certificateGenerator.SetSubjectDN(new X509Name(new ArrayList(subjectAttrs.Keys), subjectAttrs));
            certificateGenerator.SetNotBefore(DateTime.UtcNow.Date);
            certificateGenerator.SetNotAfter(DateTime.UtcNow.Date.AddYears(3));
            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            certificateGenerator.AddExtension(X509Extensions.KeyUsage, true,
                                              new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyAgreement | KeyUsage.NonRepudiation));

            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id, false,
                                              new ExtendedKeyUsage(new[] { KeyPurposeID.IdKPServerAuth }));

            GeneralNames subjectAltName = new GeneralNames(new GeneralName(GeneralName.DnsName, "SAN"));

            certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false, subjectAltName);

            Asn1SignatureFactory signatureFactory =
                new Asn1SignatureFactory(HashType.SHA256WithRSA.ToString(), subjectKeyPair.Private);

            X509Certificate certificate = certificateGenerator.Generate(signatureFactory);

            X509CertificateEntry certEntry = new X509CertificateEntry(certificate);

            Pkcs12Store store = new Pkcs12StoreBuilder().Build();

            store.SetCertificateEntry(certificate.SubjectDN.ToString(), certEntry);
            store.SetKeyEntry(certificate.SubjectDN + "_key", new AsymmetricKeyEntry(subjectKeyPair.Private),
                              new[] { certEntry });

            MemoryStream p12Stream = new MemoryStream();

            store.Save(p12Stream, request.Pin.ToCharArray(), random);

            byte[] pfx = Pkcs12Utilities.ConvertToDefiniteLength(p12Stream.ToArray(), request.Pin.ToCharArray());

            X509Certificate2 x509Certificate2 =
                new X509Certificate2(pfx, request.Pin, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);


            CreateCrl(caCert, caPrivateKey, serialNumber);

            return(FactoryResponse(x509Certificate2));
        }
Exemple #22
0
        static void Main(string[] args)
        {
            char[] passwd = "123456".ToCharArray();   //pfx密码
            IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("RSA");
            RsaKeyGenerationParameters        genPar = new RsaKeyGenerationParameters(
                BigInteger.ValueOf(0x10001), new SecureRandom(), 2048, 25);

            keyGen.Init(genPar);
            AsymmetricCipherKeyPair keypair = keyGen.GenerateKeyPair();
            RsaKeyParameters        pubKey  = (RsaKeyParameters)keypair.Public;  //CA公钥
            RsaKeyParameters        priKey  = (RsaKeyParameters)keypair.Private; //CA私钥
            Hashtable attrs = new Hashtable();
            ArrayList order = new ArrayList();

            attrs.Add(X509Name.C, "CN");                             //country code
                                                                     //attrs.Add(X509Name.ST, "Guangdong province");   //province name
                                                                     //attrs.Add(X509Name.L, "Guangzhou city");    //locality name
            attrs.Add(X509Name.O, "South China Normal University");  //organization
            attrs.Add(X509Name.OU, "South China Normal University"); //organizational unit name
            attrs.Add(X509Name.CN, "CAcert");                        //common name
            attrs.Add(X509Name.E, "*****@*****.**");
            order.Add(X509Name.C);
            //order.Add(X509Name.ST);
            //order.Add(X509Name.L);
            order.Add(X509Name.O);
            order.Add(X509Name.OU);
            order.Add(X509Name.CN);
            order.Add(X509Name.E);
            X509Name issuerDN  = new X509Name(order, attrs);
            X509Name subjectDN = issuerDN;  //自签证书,两者一样
            X509V1CertificateGenerator v1certGen = new X509V1CertificateGenerator();

            v1certGen.SetSerialNumber(new BigInteger(128, new Random()));   //128位
            v1certGen.SetIssuerDN(issuerDN);
            v1certGen.SetNotBefore(DateTime.UtcNow.AddDays(-1));
            v1certGen.SetNotAfter(DateTime.UtcNow.AddDays(365));
            v1certGen.SetSubjectDN(subjectDN);
            v1certGen.SetPublicKey(pubKey); //公钥
            v1certGen.SetSignatureAlgorithm("SHA1WithRSAEncryption");
            Org.BouncyCastle.X509.X509Certificate CAcert = v1certGen.Generate(priKey);
            CAcert.CheckValidity();
            CAcert.Verify(pubKey);

            //属性包

            /*
             * Hashtable bagAttr = new Hashtable();
             * bagAttr.Add(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id,
             *  new DerBmpString("CA's Primary Certificate"));
             * bagAttr.Add(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Id,
             *  new SubjectKeyIdentifierStructure(pubKey));
             *
             * X509CertificateEntry certEntry = new X509CertificateEntry(CAcert,bagAttr);
             */
            X509CertificateEntry certEntry = new X509CertificateEntry(CAcert);

            Pkcs12Store store = new Pkcs12StoreBuilder().Build();

            store.SetCertificateEntry("CA's Primary Certificate", certEntry);   //设置证书
            X509CertificateEntry[] chain = new X509CertificateEntry[1];
            chain[0] = certEntry;
            store.SetKeyEntry("CA's Primary Certificate", new AsymmetricKeyEntry(priKey), chain);   //设置私钥
            FileStream fout = File.Create("CA.pfx");

            store.Save(fout, passwd, new SecureRandom());   //保存
            fout.Close();
        }
Exemple #23
0
        public byte[] Export(PkiArchiveFormat format, PkiKey privateKey = null,
                             IEnumerable <PkiCertificate> chain         = null,
                             char[] password = null)
        {
            // Based on:
            //    https://stackoverflow.com/a/44798441/5428506

            switch (format)
            {
            case PkiArchiveFormat.Pem:
                using (var buff = new MemoryStream())
                {
                    byte[] bytes = privateKey?.Export(PkiEncodingFormat.Pem, password);
                    if (bytes != null)
                    {
                        buff.Write(bytes, 0, bytes.Length);
                    }
                    bytes = Export(PkiEncodingFormat.Pem);
                    buff.Write(bytes, 0, bytes.Length);
                    if (chain != null)
                    {
                        foreach (var c in chain)
                        {
                            bytes = c.Export(PkiEncodingFormat.Pem);
                            buff.Write(bytes, 0, bytes.Length);
                        }
                    }
                    return(buff.ToArray());
                }

            case PkiArchiveFormat.Pkcs12:
                var alias = AliasOf(this);
                var store = new Pkcs12StoreBuilder().Build();
                if (privateKey != null)
                {
                    store.SetKeyEntry(alias, new AsymmetricKeyEntry(privateKey.NativeKey),
                                      new[] { new X509CertificateEntry(NativeCertificate) });
                }
                else
                {
                    store.SetCertificateEntry(alias, new X509CertificateEntry(NativeCertificate));
                }

                if (chain != null)
                {
                    foreach (var c in chain)
                    {
                        store.SetCertificateEntry(AliasOf(c),
                                                  new X509CertificateEntry(c.NativeCertificate));
                    }
                }
                using (var buff = new MemoryStream())
                {
                    store.Save(buff, password ?? new char[0], new SecureRandom());
                    return(buff.ToArray());
                }

            default:
                throw new NotSupportedException();
            }
        }