General purpose writer for OpenSSL PEM objects.
        public HttpResponseMessage Get(string smsNumber, string code)
        {
            RsaKeyPairGenerator r = new RsaKeyPairGenerator();
            r.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(new Org.BouncyCastle.Security.SecureRandom(), 2048));

            AsymmetricCipherKeyPair keys = r.GenerateKeyPair();

            string publicKeyPath = Path.Combine(Path.GetTempPath(), "publicKey.key");

            if (File.Exists(publicKeyPath))
            {
                File.Delete(publicKeyPath);
            }

            using (TextWriter textWriter = new StreamWriter(publicKeyPath, false))
            {
                PemWriter pemWriter = new PemWriter(textWriter);
                pemWriter.WriteObject(keys.Public);
                pemWriter.Writer.Flush();
            }

            string certSubjectName = "UShadow_RSA";
            var certName = new X509Name("CN=" + certSubjectName);
            var serialNo = 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("sha512WithRSA");

            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 });

            using (MemoryStream ms = new MemoryStream())
            {
                store.Save(ms, "Password".ToCharArray(), new SecureRandom());

                var resp = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ByteArrayContent(ms.ToArray())
                };

                resp.Content.Headers.Add("Content-Type", "application/x-pkcs12");
                return resp;
            }
        }
 /// <summary>
 /// Gets the PEM for the Private Key from the Asymmetric Key Pair.
 /// </summary>
 /// <param name="keys"></param>
 /// <returns></returns>
 public static String GetPrivateKey(AsymmetricCipherKeyPair keys)
 {
     TextWriter textWriter = new StringWriter();
     PemWriter pemWriter = new PemWriter(textWriter);
     pemWriter.WriteObject(keys.Private);
     pemWriter.Writer.Flush();
     return textWriter.ToString();
 }
Exemple #3
0
        //https://www.rahulsingla.com/comment/219809
        public static RSAEncodedKeyPair GenerateRSAKeyPair(int strength = 1024)
        {
            RsaKeyPairGenerator g = new RsaKeyPairGenerator();

            g.Init(new KeyGenerationParameters(new SecureRandom(), strength));
            var pair = g.GenerateKeyPair();

            string privateKey = "";
            string publicKey  = "";

            using (var sw = new System.IO.StringWriter())
            {
                var pw = new PemWriter(sw);
                pw.WriteObject(pair.Private);
                privateKey = sw.ToString();
            }

            using (var sw = new System.IO.StringWriter())
            {
                var pw = new PemWriter(sw);
                pw.WriteObject(pair.Public);
                publicKey = sw.ToString();
            }

            return(new RSAEncodedKeyPair()
            {
                PrivateKey = privateKey,
                PublicKey = publicKey
            });
        }
        /// <summary>
        /// Creates a new X509 certificate and returns its data in PEM format
        /// </summary>
        public string GenerateNewCertificatePEM()
        {
            var randomGenerator      = new CryptoApiRandomGenerator();
            var random               = new SecureRandom(randomGenerator);
            var certificateGenerator = new X509V3CertificateGenerator();
            var serialNumber         = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);
            certificateGenerator.SetSignatureAlgorithm("SHA256WithRSA");
            var subjectDN = new X509Name("cn=Unknown");
            var issuerDN  = subjectDN;

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);
            certificateGenerator.SetNotBefore(DateTime.UtcNow.Date.AddYears(-10));
            certificateGenerator.SetNotAfter(DateTime.UtcNow.Date.AddYears(50));
            var keyGenerationParameters = new KeyGenerationParameters(random, 2048);
            var keyPairGenerator        = new RsaKeyPairGenerator();

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

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            X509Certificate cert = certificateGenerator.Generate(subjectKeyPair.Private);

            using (var writer = new StringWriter())
            {
                var pemWriter = new OpenSsl.PemWriter(writer);

                pemWriter.WriteObject(new PemObject("CERTIFICATE", cert.GetEncoded()));
                pemWriter.WriteObject(subjectKeyPair.Private);
                return(writer.ToString());
            }
        }
Exemple #5
0
        /// <summary>
        /// RSA密钥转Pem密钥
        /// </summary>
        /// <param name="RSAKey">RSA密钥</param>
        /// <param name="isPrivateKey">是否是私钥</param>
        /// <returns>Pem密钥</returns>
        public static string RSAKeyToPem(string RSAKey, bool isPrivateKey)
        {
            string pemKey = string.Empty;
            var    rsa    = new RSACryptoServiceProvider();

            rsa.FromXmlString(RSAKey);
            RSAParameters    rsaPara = new RSAParameters();
            RsaKeyParameters key     = null;

            //RSA私钥
            if (isPrivateKey)
            {
                rsaPara = rsa.ExportParameters(true);
                key     = new RsaPrivateCrtKeyParameters(
                    new BigInteger(1, rsaPara.Modulus), new BigInteger(1, rsaPara.Exponent), new BigInteger(1, rsaPara.D),
                    new BigInteger(1, rsaPara.P), new BigInteger(1, rsaPara.Q), new BigInteger(1, rsaPara.DP), new BigInteger(1, rsaPara.DQ),
                    new BigInteger(1, rsaPara.InverseQ));
            }
            //RSA公钥
            else
            {
                rsaPara = rsa.ExportParameters(false);
                key     = new RsaKeyParameters(false,
                                               new BigInteger(1, rsaPara.Modulus),
                                               new BigInteger(1, rsaPara.Exponent));
            }
            using (TextWriter sw = new StringWriter())
            {
                var pemWriter = new Org.BouncyCastle.OpenSsl.PemWriter(sw);
                pemWriter.WriteObject(key);
                pemWriter.Writer.Flush();
                pemKey = sw.ToString();
            }
            return(pemKey);
        }
Exemple #6
0
        private static string CreateCertificateSigningRequest(Session session, string ckaLabel, byte[] ckaId, int defaultBits,
                                                              string directDomain, string distinguishedName, int keyUsage)
        {
            // Generate key pair - Signing
            ObjectHandle publicKeyHandle;
            ObjectHandle privateKeyHandle;

            Pkcs11Util.GenerateKeyPair(session, ckaLabel, ckaId, out publicKeyHandle, out privateKeyHandle, defaultBits);

            // Generate x509 attributes for csr
            IList oids   = new ArrayList();
            IList values = new ArrayList();

            oids.Add(X509Extensions.BasicConstraints);
            values.Add(new X509Extension(
                           true,
                           new DerOctetString(new BasicConstraints(true))));

            oids.Add(X509Extensions.KeyUsage);
            values.Add(new X509Extension(
                           true,
                           new DerOctetString(new KeyUsage(keyUsage))));

            if (directDomain.Contains("@"))
            {
                AddSubjectAltNameForRfc822Name(directDomain, oids, values);
            }
            else
            {
                AddSubjectAltNameForDnsName(directDomain, oids, values);
            }

            var attribute = new AttributePkcs(
                PkcsObjectIdentifiers.Pkcs9AtExtensionRequest,
                new DerSet(new X509Extensions(oids, values)));

            var asn1Attributes = new DerSet(attribute);

            // Generate certificate request in PKCS#10 format
            byte[] pkcs10 = Pkcs11Util.GeneratePkcs10(
                session,
                publicKeyHandle,
                privateKeyHandle,
                distinguishedName,
                DigestAlgorithm.SHA256,
                asn1Attributes);

            //Export to Pem format.
            var sb        = new StringBuilder();
            var pemObject = new PemObject("CERTIFICATE REQUEST", pkcs10);

            using (var str = new StringWriter(sb))
            {
                var pemWriter = new PemWriter(str);
                pemWriter.WriteObject(pemObject);
            }

            return(sb.ToString());
        }
		private void GenerateSigningRequestViaOpenSSL(string TargetCertRequestFileName, AsymmetricCipherKeyPair KeyPair)
		{
			// We expect openssl.exe to exist in the same directory as iPhonePackager
			string OpenSSLPath = Path.GetDirectoryName( Application.ExecutablePath ) + @"\openssl.exe";
			if (!File.Exists( OpenSSLPath ))
			{
				MessageBox.Show("A version of OpenSSL is required to generate certificate requests.  Please place OpenSSL.exe in Binaries\\DotNET\\IOS", Config.AppDisplayName, MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}

			string EffectiveBuildPath = (Program.GameName.Length > 0) ? Config.BuildDirectory : Path.GetFullPath(".");

			// Create a temporary file to write the key pair out to (in a format that OpenSSL understands)
			string KeyFileName = Path.GetTempFileName();
			TextWriter KeyWriter = new StreamWriter(KeyFileName);

			PemWriter KeyWriterPEM = new PemWriter(KeyWriter);
			KeyWriterPEM.WriteObject(KeyPair);
			KeyWriter.Close();

			// Create a temporary file containing the configuration settings to drive OpenSSL
			string ConfigFileName = Path.GetTempFileName();
			TextWriter ConfigFile = new StreamWriter(ConfigFileName);
				
			ConfigFile.WriteLine("[ req ]");
			ConfigFile.WriteLine("distinguished_name     = req_distinguished_name");
			ConfigFile.WriteLine("prompt                 = no");

			ConfigFile.WriteLine("[ req_distinguished_name ]");
			ConfigFile.WriteLine("emailAddress           = {0}", EMailEditBox.Text);
			ConfigFile.WriteLine("commonName             = {0}", CommonNameEditBox.Text);
			ConfigFile.WriteLine("countryName            = {0}", System.Globalization.CultureInfo.CurrentCulture.TwoLetterISOLanguageName);

			ConfigFile.Close();

			// Invoke OpenSSL to generate the certificate request
			Program.Log("Running OpenSSL to generate certificate request...");

			string ResultsText;
			string Executable = OpenSSLPath;
			string Arguments = String.Format("req -new -nodes -out \"{0}\" -key \"{1}\" -config \"{2}\"",
				TargetCertRequestFileName, KeyFileName, ConfigFileName);
			Utilities.RunExecutableAndWait(Executable, Arguments, out ResultsText);

			Program.Log(ResultsText);

			if (!File.Exists(TargetCertRequestFileName))
			{
				Program.Error("... Failed to generate certificate request");
			}
			else
			{
				Program.Log("... Successfully generated certificate request '{0}'", TargetCertRequestFileName);
			}

			// Clean up the temporary files we created
			File.Delete(KeyFileName);
			File.Delete(ConfigFileName);
		}
        private string GeneratePemFromObject(object input)
        {
            var builder = new StringBuilder();
            var writer = new PemWriter(new StringWriter(builder));

            writer.WriteObject(new MiscPemGenerator(input));
            writer.Writer.Flush();

            return builder.ToString();
        }
 public string DecodePublicKey(string filename)
 {
     byte[] dataKey = System.IO.File.ReadAllBytes(filename);
     AsymmetricKeyParameter asp = PublicKeyFactory.CreateKey(dataKey);
     System.IO.MemoryStream ms = new System.IO.MemoryStream();
     System.IO.TextWriter writer = new System.IO.StreamWriter(ms);
     System.IO.StringWriter stWrite = new System.IO.StringWriter();
     PemWriter pmw = new PemWriter(stWrite);
     pmw.WriteObject(asp);
     stWrite.Close();
     return stWrite.ToString();
 }
 /// <summary>
 /// PEM representation of X509 certificate
 /// </summary>
 /// <param name="certificate">Certificate to get PEM representation for</param>
 /// <returns>PEM representation for certificate</returns>
 public string ExportCertificate(X509Certificate certificate)
 {
     using (var memoryStream = new MemoryStream())
     {
         using (var streamWriter = new StreamWriter(memoryStream))
         {
             var pemWriter = new PemWriter(streamWriter);
             pemWriter.WriteObject(certificate);
             streamWriter.Flush();
             return Encoding.ASCII.GetString(memoryStream.GetBuffer());
         }
     }
 }
Exemple #11
0
        /// <summary>
        /// 获取pem字符串
        /// </summary>
        /// <param name="cert"></param>
        /// <returns></returns>
        public static string GetPublicKeyPem(X509Certificate2 cert)
        {
            var p   = cert.GetRSAPublicKey().ExportParameters(false);
            var key = new RsaKeyParameters(false, new BigInteger(1, p.Modulus), new BigInteger(1, p.Exponent));



            using (var stringWriter = new StringWriter())
            {
                var pemWriter = new Org.BouncyCastle.OpenSsl.PemWriter(stringWriter);
                pemWriter.WriteObject(key);
                return(stringWriter.GetStringBuilder().ToString());
            }
        }
 /// <summary>
 /// Crea un archivo .PEM partiendo del certificado.
 /// </summary>
 /// <param name="rutaCertificado"></param>
 /// <param name="RutaCerticadoPEM"></param>
 public void CreaArchivoExtPEM(String rutaCertificado, String RutaCerticadoPEM)
 {
     if (!File.Exists(RutaCerticadoPEM))
     {
         Stream sr = File.OpenRead(rutaCertificado);
         X509CertificateParser cp = new X509CertificateParser();
         Org.BouncyCastle.X509.X509Certificate cert = cp.ReadCertificate(sr);
         Object     pkey = cert.GetPublicKey();
         TextWriter tw   = new System.IO.StreamWriter(RutaCerticadoPEM);
         Org.BouncyCastle.OpenSsl.PemWriter pw = new Org.BouncyCastle.OpenSsl.PemWriter(tw);
         pw.WriteObject(cert);
         tw.Close();
     }
 }
Exemple #13
0
 static string WriteKeyAsPem(AsymmetricCipherKeyPair pair, int type)
 {
     using (TextWriter textWriter = new StringWriter())
     {
         var pemWriter = new Org.BouncyCastle.OpenSsl.PemWriter(textWriter);
         if (type == 0)
         {
             pemWriter.WriteObject(pair.Public);
         }
         else
         {
             pemWriter.WriteObject(pair.Private);
         }
         return(textWriter.ToString());
     }
 }
Exemple #14
0
        //
        // Bouncy Castle PKCS#8 Formater
        // Output is the same as this OpenSSL command:
        // openssl pkcs12 -in certname.pfx -nocerts -out key.pem -nodes
        //
        private string GetPkcs8Format(RSACryptoServiceProvider csp)
        {
            var rsaParams = csp.ExportParameters(true);
            var keyPair   = DotNetUtilities.GetRsaKeyPair(rsaParams);
            var pkcs8Gen  = new Pkcs8Generator(keyPair.Private);
            var pemObj    = pkcs8Gen.Generate();
            var sb        = new StringBuilder();

            using (var pkcs8Out = new StringWriter(sb))
            {
                var pemWriter = new PemWriter(pkcs8Out);
                pemWriter.WriteObject(pemObj);
            }

            return(sb.ToString());
        }
        public static void ExportPEMPrivateKey(X509Certificate2 certificate, string filePath)
        {
            if (certificate.PrivateKey == null)
            {
                return;
            }

            var keyPair = DotNetUtilities.GetKeyPair(certificate.PrivateKey);

            using (TextWriter tw = new StreamWriter(filePath))
            {
                PemWriter pemWriter = new Org.BouncyCastle.OpenSsl.PemWriter(tw);
                pemWriter.WriteObject(keyPair.Private);
                tw.Flush();
                tw.Close();
            }
        }
 /// <summary>
 ///     Generates a PKCS private key from the PowerRSA object
 /// </summary>
 /// <param name="prsa"></param>
 /// <returns></returns>
 public static string ConvertPrivateKeyToPKCS(PowerRSA prsa)
 {
     var rsa = RSA.Create();
     rsa.FromXmlString(prsa.PrivateKey);
     var bcKeyPair = DotNetUtilities.GetRsaKeyPair(rsa);
     var pkcs8Gen = new Pkcs8Generator(bcKeyPair.Private);
     var pemObj = pkcs8Gen.Generate();
     string outputPem;
     using (var sw = new StringWriter())
     {
         var pkcs8Out = sw;
         var pemWriter = new PemWriter(pkcs8Out);
         pemWriter.WriteObject(pemObj);
         pkcs8Out.Close();
         outputPem = sw.ToString();
     }
     return outputPem;
 }
Exemple #17
0
        public static string LoadPrivateKey(string fileName, string password)
        {
            AsymmetricKeyParameter akp;
            StringWriter str_writer;
            PemWriter pem_writer;
            byte[] dataKey;

            str_writer = new StringWriter ();

            dataKey = File.ReadAllBytes (fileName);
            akp = PrivateKeyFactory.DecryptKey (password.ToCharArray (), dataKey);

            pem_writer = new PemWriter (str_writer);
            pem_writer.WriteObject (akp);

            str_writer.Close ();

            return str_writer.ToString ();
        }
        /// <summary>
        /// PEM representation of the key pair
        /// </summary>
        /// <param name="keyPair">Key value pair</param>
        /// <returns>Key pair in pem format</returns>
        public string ExportKeyPair(AsymmetricCipherKeyPair keyPair)
        {
            // using Bouncy Castle, so that we are 100% sure that the result is exaclty the same as:
            // openssl pkcs12 -in filename.pfx -nocerts -out privateKey.pem
            // openssl rsa -in privateKey.pem -out private.pem

            using (var memoryStream = new MemoryStream())
            {
                using (var streamWriter = new StreamWriter(memoryStream))
                {
                    var pemWriter = new PemWriter(streamWriter);
                    pemWriter.WriteObject(keyPair.Private);
                    streamWriter.Flush();

                    // Here is the output with ---BEGIN RSA PRIVATE KEY---
                    // that should be exactly the same as in private.pem
                    return Encoding.ASCII.GetString(memoryStream.GetBuffer());
                }
            }
        }
Exemple #19
0
        /// <summary>
        /// 获取私钥
        /// </summary>
        /// <param name="cert"></param>
        /// <returns></returns>
        public static string GetPrivateKeyPem(X509Certificate2 cert)
        {
            try
            {
                var p   = cert.GetRSAPrivateKey().ExportParameters(true);
                var key = new RsaPrivateCrtKeyParameters(
                    new Org.BouncyCastle.Math.BigInteger(1, p.Modulus), new Org.BouncyCastle.Math.BigInteger(1, p.Exponent), new Org.BouncyCastle.Math.BigInteger(1, p.D),
                    new Org.BouncyCastle.Math.BigInteger(1, p.P), new Org.BouncyCastle.Math.BigInteger(1, p.Q), new Org.BouncyCastle.Math.BigInteger(1, p.DP), new Org.BouncyCastle.Math.BigInteger(1, p.DQ),
                    new Org.BouncyCastle.Math.BigInteger(1, p.InverseQ));


                using (var stringWriter = new StringWriter())
                {
                    var pemWriter = new Org.BouncyCastle.OpenSsl.PemWriter(stringWriter);
                    pemWriter.WriteObject(key);
                    return(stringWriter.GetStringBuilder().ToString());
                }
            }
            catch
            {
                throw new Exception("cert必须具有 X509KeyStorageFlags.Exportable 标识,才能导出私钥。");
            }
        }
Exemple #20
0
        /// <summary>
        /// Export a certificate to a PEM format string
        /// </summary>
        /// <param name="cert">The certificate to export</param>
        /// <returns>A PEM encoded string</returns>
        public static string ExportToPEM(X509Certificate cert)
        {
            StringWriter swriter = new StringWriter();
            PemWriter writer = new PemWriter(swriter);

            writer.WriteObject(new X509.X509CertificateParser().ReadCertificate(cert.Export(X509ContentType.Cert)));

            return swriter.ToString();
        }
Exemple #21
0
 public override void Serialize(Stream aStream, object aObject)
 {
     /* check for required parameters */
       if (aStream == null) {
     throw new ArgumentNullException("aStream");
       }
       if (aObject == null) {
     throw new ArgumentNullException("aObject");
       }
       PasswordFinder pwFinder = null;
       if (GetPassphraseCallbackMethod != null) {
     pwFinder = new PasswordFinder(GetPassphraseCallbackMethod);
       }
       StreamWriter streamWriter = new StreamWriter(aStream);
       PemWriter writer = new PemWriter(streamWriter);
       PinnedArray<char> passphrase = null;
       if (pwFinder != null) {
     passphrase = new PinnedArray<char>(0);
     passphrase.Data = pwFinder.GetPassword();
       }
       if (passphrase == null) {
     writer.WriteObject(aObject);
       } else {
     writer.WriteObject(aObject, null, passphrase.Data, null);
     passphrase.Dispose();
       }
 }
        private async Task SaveCertKeyPair()
        {
            var settings = ApplicationData.Current.RoamingSettings;
            PemWriter certWriter = new PemWriter(new StringWriter());
            PemWriter keyWriter = new PemWriter(new StringWriter());

            keyWriter.WriteObject(keyPair);
            keyWriter.Writer.Flush();

            // Add the cert to the cert store. This changes the fingerprint so we read it
            // back before we serialize it so we have the up to date cert.
            await AddToWinCertStore();

            // Read the modified cert from the cert store
            IEnumerable<Certificate> certificates = await CertificateStores.FindAllAsync(new CertificateQuery { FriendlyName = "Limelight-Client" });
            cert = new X509CertificateParser().ReadCertificate(certificates.Single().GetCertificateBlob().AsStream());

            certWriter.WriteObject(cert);
            certWriter.Writer.Flush();

            // Line endings MUST be UNIX for the PC to accept the cert properly
            string keyStr = keyWriter.Writer.ToString();
            keyStr = keyStr.Replace("\r\n", "\n");

            string certStr = certWriter.Writer.ToString();
            certStr = certStr.Replace("\r\n", "\n");

            settings.Values["cert"] = certStr;
            settings.Values["key"] = keyStr;
        }
Exemple #23
0
        /// <summary>
        /// Export an RSA key to a PEM format string
        /// </summary>
        /// <param name="rsa">The RSA key to export (must be exportable)</param>
        /// <param name="password">An optional password</param>
        /// <returns>A PEM string form of the key</returns>
        public static string ExportToPEM(RSA rsa, SecureString password)
        {
            StringWriter swriter = new StringWriter();
            PemWriter writer = new PemWriter(swriter);

            RSAParameters ps = rsa.ExportParameters(true);

            BigInteger modulus = new BigInteger(1, ps.Modulus);
            BigInteger exp = new BigInteger(1, ps.Exponent);
            BigInteger d = new BigInteger(1, ps.D);
            BigInteger p = new BigInteger(1, ps.P);
            BigInteger q = new BigInteger(1, ps.Q);
            BigInteger dp = new BigInteger(1, ps.DP);
            BigInteger dq = new BigInteger(1, ps.DQ);
            BigInteger qinv = new BigInteger(1, ps.InverseQ);

            RsaPrivateCrtKeyParameters privKey = new RsaPrivateCrtKeyParameters(modulus, exp, d, p, q, dp, dq, qinv);

            if (password != null)
            {
                writer.WriteObject(privKey, "DES-EDE3-CBC",
                    SecureStringToCharArray(password), new Org.BouncyCastle.Security.SecureRandom());
            }
            else
            {
                writer.WriteObject(privKey);
            }

            return swriter.ToString();
        }
        /// <summary>
        /// Erstellt die für die PKCS#10-Datei notwendigen Daten
        /// </summary>
        /// <returns>Die für die PKCS#10-Datei notwendigen Daten</returns>
        public Pkcs10Data CreateRequest()
        {
            var sigAlgoName = "SHA256WITHRSA";
            var subject = new X509Name(
                true,
                $"CN={Requester.Surname}, OU={Requester.Number}, OU={Requester.CompanyName}, O={"ITSG TrustCenter fuer Arbeitgeber"}, C={"DE"}",
                new Pkcs.X509ItsgEntryConverter()
            );

            var rng = new SecureRandom();
            var rsaKeyPair = RSA;
            if (rsaKeyPair == null)
            {
                var keyPairGen = new RsaKeyPairGenerator();
                keyPairGen.Init(new KeyGenerationParameters(rng, 2048));
                rsaKeyPair = keyPairGen.GenerateKeyPair();
            }
            var csr = new Pkcs10CertificationRequest(sigAlgoName, subject, rsaKeyPair.Public, null, rsaKeyPair.Private);
            
            var outputCsrPem = new StringWriter();
            {
                var pemWriter = new PemWriter(outputCsrPem);
                pemWriter.WriteObject(csr);
            }

            var outputPrivateKeyPem = new StringWriter();
            {
                var pemWriter = new PemWriter(outputPrivateKeyPem);
                if (string.IsNullOrEmpty(Password))
                {
                    pemWriter.WriteObject(rsaKeyPair.Private);
                }
                else
                {
                    pemWriter.WriteObject(
                        rsaKeyPair.Private,
                        "des-ede3-cbc",
                        Password.ToCharArray(),
                        rng
                    );
                }
            }

            var rsaPubKey = (RsaKeyParameters)rsaKeyPair.Public;
            var rawPubKeyData = OstcUtils.CalculatePublicKeyHash(rsaPubKey);

            return new Pkcs10Data(csr.GetEncoded(), outputCsrPem.ToString(), outputPrivateKeyPem.ToString(), rawPubKeyData);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <remarks>Based on <see cref="http://www.fkollmann.de/v2/post/Creating-certificates-using-BouncyCastle.aspx"/></remarks>
        /// <param name="subjectName"></param>
        /// <returns></returns>
        public static void z_dep_GenerateCertificate(string subjectName, long serialNumber, DateTime expireOn, System.Security.Cryptography.X509Certificates.X509Certificate2 issuingCertificate, out string thumbprint, out string pemPrivateKey, out string pemPublicCert, out byte[] publicCert, out byte[] pkcs12Data, out string password)
        {

            AsymmetricKeyParameter caPrivateKey;
            var caCert = ReadCertificateFromX509Certificate2(issuingCertificate, out caPrivateKey);

            //var caAuth = new AuthorityKeyIdentifierStructure(caCert);
            //var authKeyId = new AuthorityKeyIdentifier(caAuth.GetKeyIdentifier());

            // ---------------------------

            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random = new SecureRandom(randomGenerator);

            var gen = new X509V3CertificateGenerator();

            // var certName = new X509Name("CN=" + subjectName);

            var list = new Dictionary<string, string>();
            AddItems(list, "CN", subjectName);
            AddItems(list, "O", "CompliaShield");
            AddItems(list, "OU", "CompliaShield");
            //var simpleCertName = GetItemString(list);
            //var certNameLight = new X509Name(simpleCertName);

            list.Add("L", "Boulder");
            list.Add("ST", "Colorado");
            list.Add("C", "US");
            var subjectFull = GetItemString(list);
            var certName = new X509Name(subjectFull);


            BigInteger serialNo;
            if (serialNumber == 0)
            {
                serialNo = BigInteger.ProbablePrime(120, random);
            }
            else
            {
                serialNo = BigInteger.ValueOf(serialNumber);
            }
            gen.SetSerialNumber(serialNo);
            gen.SetSubjectDN(certName);

            gen.SetIssuerDN(caCert.IssuerDN);

            var issuerPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(caCert.GetPublicKey());
            var issuerGeneralNames = new GeneralNames(new GeneralName(caCert.IssuerDN));
            var issuerSerialNumber = caCert.SerialNumber;

            var authorityKeyIdentifier = new AuthorityKeyIdentifier(issuerPublicKeyInfo, issuerGeneralNames, issuerSerialNumber);
            gen.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, true, authorityKeyIdentifier);

            // gen.SetIssuerUniqueID(caCert.IssuerUniqueID.GetBytes())

            gen.SetNotAfter(expireOn);
            gen.SetNotBefore(DateTime.Now.AddHours(-2));
            gen.SetSignatureAlgorithm("SHA256WithRSA"); //("MD5WithRSA");

            var kpgen = new RsaKeyPairGenerator();
            kpgen.Init(new KeyGenerationParameters(random, 2048)); // new SecureRandom(new CryptoApiRandomGenerator()), 2048));
            var subjectKeyPair = kpgen.GenerateKeyPair();
            gen.SetPublicKey(subjectKeyPair.Public);

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

            //1.3.6.1.5.5.7.3.1 = server authentication
            //1.3.6.1.5.5.7.3.2 = client authentication
            //1.3.6.1.5.5.7.3.3 = code signing

            var certificate = gen.Generate(caPrivateKey);

            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);

            // merge into X509Certificate2
            var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());
            var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded());
            if (seq.Count != 9)
            {
                throw new PemException("Malformed sequence in RSA private key.");
            }

            var rsa = new RsaPrivateKeyStructure(seq);
            RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            //-------------

            //RsaPrivateCrtKeyParameters rsaparams = (RsaPrivateCrtKeyParameters)subjectKeyPair.Private;
            RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(rsaparams);
            CspParameters cspParameters = new CspParameters();
            cspParameters.KeyContainerName = Guid.NewGuid().ToString(); // "MyKeyContainer";
            RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(2048, cspParameters);
            rsaKey.ImportParameters(rsaParameters);

            // ------------

            x509.PrivateKey = rsaKey; // DotNetUtilities.ToRSA(rsaparams);

            // Generating Random Numbers
            var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-()#$%^&@+=!{}[]*.,";
            var rnd = new Random();

            password = new string(
                Enumerable.Repeat(chars, 32)
                          .Select(s => s[rnd.Next(s.Length)])
                          .ToArray());
            thumbprint = x509.Thumbprint.ToLower();
            publicCert = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert);

            var privateKeyPem = new StringBuilder();
            var privateKeyPemWriter = new PemWriter(new StringWriter(privateKeyPem));
            privateKeyPemWriter.WriteObject(certificate);
            privateKeyPemWriter.WriteObject(subjectKeyPair.Private);
            privateKeyPemWriter.Writer.Flush();
            pemPrivateKey = privateKeyPem.ToString();

            var publicKeyPem = new StringBuilder();
            var utf8WithoutBom = new System.Text.UTF8Encoding(false);
            var publicKeyPemWriter = new PemWriter(new StringWriterWithEncoding(publicKeyPem, utf8WithoutBom));
            publicKeyPemWriter.WriteObject(certificate);
            publicKeyPemWriter.Writer.Flush();
            pemPublicCert = publicKeyPem.ToString();
            pemPublicCert = pemPublicCert.Replace(Environment.NewLine, "\n"); //only use newline and not returns

            pkcs12Data = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pfx, password);

        }
Exemple #26
0
        public void GenerateKeyPairs()
        {
            var keyPair = GetKeyPair();
            var publicKey = (RsaKeyParameters) keyPair.Public;
            var privateKey = (RsaKeyParameters) keyPair.Private;


            var publicWriter = new StringWriter();
            var pemWriter = new PemWriter(publicWriter);
            pemWriter.WriteObject(publicKey);
            pemWriter.Writer.Flush();
            PublicKey = StringToSecureString(Base64Encode(publicWriter.ToString()));
            publicWriter.Close();

            var privateWriter = new StringWriter();
            var pemWriterP = new PemWriter(privateWriter);
            pemWriterP.WriteObject(privateKey);
            pemWriterP.Writer.Flush();
            PrivateKey = StringToSecureString(Base64Encode(privateWriter.ToString()));
            privateWriter.Close();
        }
        public static void GenerateRootCertificate(string subjectName, long serialNumber, DateTime expireOn, bool isCertificateAuthority, out string thumbprint, out string pemPrivateKey, out string pemPublicCert, out byte[] publicCert, out byte[] pkcs12Data, out string password)
        {

            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random = new SecureRandom(randomGenerator);

            var kpgen = new RsaKeyPairGenerator();
            kpgen.Init(new KeyGenerationParameters(random, 2048)); //new SecureRandom(new CryptoApiRandomGenerator()), 2048));
            var subjectKeyPair = kpgen.GenerateKeyPair();

            var gen = new X509V3CertificateGenerator();

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

            BigInteger serialNo;
            if (serialNumber == 0)
            {
                serialNo = BigInteger.ProbablePrime(120, random);
            }
            else
            {
                serialNo = BigInteger.ValueOf(serialNumber);
            }

            gen.SetSerialNumber(serialNo);
            gen.SetSubjectDN(certName);
            gen.SetIssuerDN(certName);

            gen.SetNotAfter(expireOn);
            gen.SetNotBefore(DateTime.Now.Date);
            gen.SetSignatureAlgorithm("SHA256WithRSA"); //("MD5WithRSA");
            gen.SetPublicKey(subjectKeyPair.Public);


            gen.AddExtension(
                X509Extensions.BasicConstraints.Id,
                true,
                new BasicConstraints(isCertificateAuthority));


            //// NOT WORKING... NOT PASSING CERTIFICATE ISSUING ALLOWED
            //if (isCertificateAuthority)
            //{
            //    gen.AddExtension(
            //         X509Extensions.BasicConstraints.,
            //         true,
            //         new BasicConstraints(isCertificateAuthority));
            //}



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

            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);
            var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());
            var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded());
            if (seq.Count != 9)
            {
                throw new PemException("Malformed sequence in RSA private key.");
            }

            var rsa = new RsaPrivateKeyStructure(seq);
            RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(rsaparams);
            CspParameters cspParameters = new CspParameters();
            cspParameters.KeyContainerName = Guid.NewGuid().ToString(); // "MyKeyContainer";
            RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(2048, cspParameters);
            rsaKey.ImportParameters(rsaParameters);

            x509.PrivateKey = rsaKey; // DotNetUtilities.ToRSA(rsaparams);

            // Generating Random Numbers
            var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-()#$%^&@+=!";
            var rnd = new Random();

            password = new string(
                Enumerable.Repeat(chars, 32)
                          .Select(s => s[rnd.Next(s.Length)])
                          .ToArray());
            thumbprint = x509.Thumbprint.ToLower();
            publicCert = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert);

            var privateKeyPem = new StringBuilder();
            var privateKeyPemWriter = new PemWriter(new StringWriter(privateKeyPem));
            privateKeyPemWriter.WriteObject(certificate);
            privateKeyPemWriter.WriteObject(subjectKeyPair.Private);
            privateKeyPemWriter.Writer.Flush();
            pemPrivateKey = privateKeyPem.ToString();

            var publicKeyPem = new StringBuilder();
            var utf8WithoutBom = new System.Text.UTF8Encoding(false);
            var publicKeyPemWriter = new PemWriter(new StringWriterWithEncoding(publicKeyPem, utf8WithoutBom));
            publicKeyPemWriter.WriteObject(certificate);
            publicKeyPemWriter.Writer.Flush();
            pemPublicCert = publicKeyPem.ToString();
            pemPublicCert = pemPublicCert.Replace(Environment.NewLine, "\n"); //only use newline and not returns

            pkcs12Data = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pfx, password);
        }
Exemple #28
0
        public static void WriteRSAKeys(AsymmetricCipherKeyPair Keys, string Path)
        {
            AsymmetricKeyParameter PublicKey = Keys.Public;
            AsymmetricKeyParameter PrivateKey = Keys.Private;
            string Extension = System.IO.Path.GetExtension(Path);
            string PublicPath = (Extension.Length != 0) ? Path.Replace(Extension, "_public" + Extension) : Path + "_public";
            string PrivatePath = (Extension.Length != 0) ? Path.Replace(Extension, "_private" + Extension) : Path + "_private";

            TextWriter tw = new StreamWriter(PublicPath);
            PemWriter pw = new PemWriter(tw);
            pw.WriteObject(PublicKey);
            pw.Writer.Flush();
            pw.Writer.Close();
            tw.Close();

            tw = new StreamWriter(PrivatePath);
            pw = new PemWriter(tw);
            pw.WriteObject(PrivateKey);
            pw.Writer.Flush();
            pw.Writer.Close();
            tw.Close();
        }
Exemple #29
0
        public string getXmrPublicKey()
        {
            AsymmetricCipherKeyPair key = getXmrKey();

            using (TextWriter textWriter = new StringWriter())
            {
                PemWriter writer = new PemWriter(textWriter);
                writer.WriteObject(key.Public);
                writer.Writer.Flush();

                return textWriter.ToString();                
            }
        }
 public string GetPemData()
 {
     var textWriter = new StringWriter();
     var pemWriter = new PemWriter(textWriter);
     pemWriter.WriteObject(KeyPair.Private, "DESEDE", UserPassword.ToCharArray(), new SecureRandom());
     pemWriter.Writer.Flush();
     return textWriter.ToString();
 }
		/**
		 * Returns the encoded form of this certification path, using
		 * the specified encoding.
		 *
		 * @param encoding the name of the encoding to use
		 * @return the encoded bytes
		 * @exception CertificateEncodingException if an encoding error
		 * occurs or the encoding requested is not supported
		 *
		 */
		public virtual byte[] GetEncoded(
			string encoding)
		{
			if (Platform.CompareIgnoreCase(encoding, "PkiPath") == 0)
			{
				Asn1EncodableVector v = new Asn1EncodableVector();

				for (int i = certificates.Count - 1; i >= 0; i--)
				{
					v.Add(ToAsn1Object((X509Certificate) certificates[i]));
				}

				return ToDerEncoded(new DerSequence(v));
			}
            else if (Platform.CompareIgnoreCase(encoding, "PKCS7") == 0)
			{
				Asn1.Pkcs.ContentInfo encInfo = new Asn1.Pkcs.ContentInfo(
					PkcsObjectIdentifiers.Data, null);

				Asn1EncodableVector v = new Asn1EncodableVector();
				for (int i = 0; i != certificates.Count; i++)
				{
					v.Add(ToAsn1Object((X509Certificate)certificates[i]));
				}

				Asn1.Pkcs.SignedData sd = new Asn1.Pkcs.SignedData(
					new DerInteger(1),
					new DerSet(),
					encInfo,
					new DerSet(v),
					null,
					new DerSet());

				return ToDerEncoded(new Asn1.Pkcs.ContentInfo(PkcsObjectIdentifiers.SignedData, sd));
			}
            else if (Platform.CompareIgnoreCase(encoding, "PEM") == 0)
			{
				MemoryStream bOut = new MemoryStream();
				PemWriter pWrt = new PemWriter(new StreamWriter(bOut));

				try
				{
					for (int i = 0; i != certificates.Count; i++)
					{
						pWrt.WriteObject(certificates[i]);
					}

					pWrt.Writer.Close();
				}
				catch (Exception)
				{
					throw new CertificateEncodingException("can't encode certificate for PEM encoded path");
				}

				return bOut.ToArray();
			}
			else
			{
				throw new CertificateEncodingException("unsupported encoding: " + encoding);
			}
		}
 public void generateCSR(string electoralEampaign, string user, string password)
 {
     X509Name name = new X509Name("C=PL, ST=Mazowieckie, L=Warszawa, O=KBW, E=-, OU=" + electoralEampaign + ", CN=" + user);
     RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator();
     RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(BigInteger.ValueOf(3L), new SecureRandom(), 2048, 25);
     keyGenerator.Init(param);
     AsymmetricCipherKeyPair ackp = keyGenerator.GenerateKeyPair();
     Pkcs10CertificationRequest csr = new Pkcs10CertificationRequest("SHA1WITHRSA", name, ackp.Public, null, ackp.Private);
     System.Text.StringBuilder CSRPem = new System.Text.StringBuilder();
     PemWriter CSRPemWriter = new PemWriter(new System.IO.StringWriter(CSRPem));
     CSRPemWriter.WriteObject(csr);
     CSRPemWriter.Writer.Flush();
     this.generatedCSR = CSRPem.ToString();
     System.Text.StringBuilder PrivateKeyPem = new System.Text.StringBuilder();
     PemWriter PrivateKeyPemWriter = new PemWriter(new System.IO.StringWriter(PrivateKeyPem));
     PrivateKeyPemWriter.WriteObject(ackp.Private);
     CSRPemWriter.Writer.Flush();
     this.keys = PrivateKeyPem.ToString();
     AsymmetricKeyParameter publicKey = ackp.Public;
     AsymmetricKeyParameter privateKey = ackp.Private;
     System.IO.StringWriter sw = new System.IO.StringWriter();
     PemWriter pw = new PemWriter(sw);
     pw.WriteObject(privateKey, "AES-256-CBC", password.ToCharArray(), new SecureRandom());
     pw.Writer.Close();
     this.keys = sw.ToString();
     if (!System.IO.Directory.Exists(this.path + "\\Licenses"))
     {
         try
         {
             System.IO.Directory.CreateDirectory(this.path + "\\Licenses");
         }
         catch (System.ArgumentNullException)
         {
             MessageBox.Show("Nieprawidłowa ścieżka. Nie można utworzyć katalogu \"Licenses\"", "Error");
         }
         catch (System.ArgumentException)
         {
             MessageBox.Show("Nieprawidłowa ścieżka. Nie można utworzyć katalogu \"Licenses\"", "Error");
         }
         catch (System.UnauthorizedAccessException)
         {
             MessageBox.Show("Nie masz uprawnień do tworzenia katalogów. Otwórz aplikacje jako adnimistrator.", "Uwaga");
         }
         catch (System.IO.PathTooLongException)
         {
             MessageBox.Show("Nieprawidłowa ścieżka. Nie można utworzyć katalogu \"Licenses\"", "Error");
         }
         catch (System.IO.DirectoryNotFoundException)
         {
             MessageBox.Show("Nieprawidłowa ścieżka. Nie można utworzyć katalogu \"Licenses\"", "Error");
         }
         catch (System.NotSupportedException)
         {
             MessageBox.Show("Nieprawidłowy format ścieżki. Nie można utworzyć katalogu \"Licenses\"", "Error");
         }
         catch (System.IO.IOException)
         {
             MessageBox.Show("Nieprawidłowa ścieżka. Nie można utworzyć katalogu \"Licenses\"", "Error");
         }
     }
     string namefile = "";
     try
     {
         int tmp = System.IO.Directory.GetFiles(this.path + "\\Licenses", electoralEampaign.Replace("/", "_") + "_" + user + "*.csr").Length + 1;
         if (tmp > 1)
         {
             string num = tmp.ToString();
             namefile = string.Concat(new string[]
             {
                 electoralEampaign.Replace("/", "_"),
                 "_",
                 user,
                 " ",
                 num
             });
         }
         else
         {
             namefile = electoralEampaign.Replace("/", "_") + "_" + user;
         }
     }
     catch (System.Exception)
     {
         namefile = electoralEampaign.Replace("/", "_") + "_" + user;
     }
     try
     {
         System.IO.StreamWriter sw2 = new System.IO.StreamWriter(this.path + "\\Licenses\\" + namefile + ".csr", false);
         sw2.Write(this.generatedCSR);
         sw2.Close();
         sw2 = new System.IO.StreamWriter(this.path + "\\Licenses\\" + namefile + ".key", false);
         sw2.Write(this.keys);
         sw2.Close();
     }
     catch (System.ArgumentNullException)
     {
         MessageBox.Show("Błędna ścieżka", "Error");
     }
     catch (System.ArgumentException)
     {
         MessageBox.Show("Błędna ścieżka", "Error");
     }
     catch (System.IO.DirectoryNotFoundException)
     {
         MessageBox.Show("Nie znaleziono katalogu", "Error");
     }
     catch (System.IO.PathTooLongException)
     {
         MessageBox.Show("Zbyt długa ścieżka do katalogu", "Error");
     }
     catch (System.IO.IOException)
     {
         MessageBox.Show("Podano ścieżke do pliku zamiast katalogu", "Error");
     }
     catch (System.UnauthorizedAccessException)
     {
         MessageBox.Show("Program nie posiada uprawnień do zapisywania plików. Otwórz aplikacje jako Administrator", "Error");
     }
     catch (System.Exception e)
     {
         MessageBox.Show("Nie można zapisać pliku. Orginal error: " + e.Message, "Error");
     }
 }
Exemple #33
0
 private static string pemEncode(AsymmetricKeyParameter key)
 {
     System.IO.TextWriter textWriter = new StringWriter();
     PemWriter pemWriter = new PemWriter(textWriter);
     pemWriter.WriteObject(key);
     pemWriter.Writer.Flush();
     string encoded = textWriter.ToString();
     var splited = encoded.Split(new string[] { textWriter.NewLine }, StringSplitOptions.None);
     //Console.WriteLine(encoded);
     return encoded;
 }
        public void TestMethod1()
        {
            // this snippet can be easily used in any normal c# project as well by simply removing the .Dump() methods
            // and saving the output into a variable / file of your choice.
            // you'll need to add BouncyCastle.Crypto nuget to use this.
            // tested on 1.8.0-beta4

            AsymmetricCipherKeyPair pair;
            Pkcs10CertificationRequest csr;

            var ecMode = false;
            var values = new Dictionary<DerObjectIdentifier, string> {
    {X509Name.CN, ""}, //domain name
    {X509Name.OU, "Domain Control Validated"},
    {X509Name.O, ""}, //Organisation's Legal name
    {X509Name.L, "London"},
    {X509Name.ST, "England"},
    {X509Name.C, "GB"},
};

            var subjectAlternateNames = new GeneralName[] { };

            var extensions = new Dictionary<DerObjectIdentifier, X509Extension>()
{
    {X509Extensions.BasicConstraints, new X509Extension(true, new DerOctetString(new BasicConstraints(false)))},
    {X509Extensions.KeyUsage, new X509Extension(true, new DerOctetString(new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyEncipherment | KeyUsage.DataEncipherment | KeyUsage.NonRepudiation)))},
    {X509Extensions.ExtendedKeyUsage, new X509Extension(false, new DerOctetString(new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth)))},
};

            if (values[X509Name.CN].StartsWith("www.")) values[X509Name.CN] = values[X509Name.CN].Substring(4);

            if (!values[X509Name.CN].StartsWith("*.") && subjectAlternateNames.Length == 0)
                subjectAlternateNames = new GeneralName[] { new GeneralName(GeneralName.DnsName, $"www.{values[X509Name.CN]}") };

            if (subjectAlternateNames.Length > 0) extensions.Add(X509Extensions.SubjectAlternativeName, new X509Extension(false, new DerOctetString(new GeneralNames(subjectAlternateNames))));

            var subject = new X509Name(values.Keys.Reverse().ToList(), values);

            if (ecMode)
            {
                var gen = new ECKeyPairGenerator();
                var ecp = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp384r1");
                gen.Init(new ECKeyGenerationParameters(new ECDomainParameters(ecp.Curve, ecp.G, ecp.N, ecp.H, ecp.GetSeed()), new SecureRandom()));

                pair = gen.GenerateKeyPair();

                extensions.Add(X509Extensions.SubjectKeyIdentifier, new X509Extension(false, new DerOctetString(new SubjectKeyIdentifierStructure(pair.Public))));
                csr = new Pkcs10CertificationRequest("SHA256withECDSA", subject, pair.Public, new DerSet(new AttributePkcs(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, new DerSet(new X509Extensions(extensions)))), pair.Private);

            }
            else
            {
                var gen = new RsaKeyPairGenerator();
                gen.Init(new KeyGenerationParameters(new SecureRandom(), 2048));

                pair = gen.GenerateKeyPair();
                extensions.Add(X509Extensions.SubjectKeyIdentifier, new X509Extension(false, new DerOctetString(new SubjectKeyIdentifierStructure(pair.Public))));
                csr = new Pkcs10CertificationRequest("SHA256withRSA", subject, pair.Public, new DerSet(new AttributePkcs(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, new DerSet(new X509Extensions(extensions)))), pair.Private);
            }

            //Convert BouncyCastle csr to .PEM file.
            var csrPem = new StringBuilder();
            var csrPemWriter = new PemWriter(new StringWriter(csrPem));
            csrPemWriter.WriteObject(csr);
            csrPemWriter.Writer.Flush();

            Console.WriteLine(csrPem.ToString());

            var privateKeyPem = new StringBuilder();
            var privateKeyPemWriter = new PemWriter(new StringWriter(privateKeyPem));
            privateKeyPemWriter.WriteObject(pair.Private);
            csrPemWriter.Writer.Flush();

            //privateKeyPem.ToString().Dump("Private Key");
        }
        private static void GenerateSigningCertificate(ICertificatePolicy certificatePolicy, out string thumbprint, out string pemPublicCert, out byte[] pkcs12Data, out System.Security.Cryptography.X509Certificates.X509Certificate2 x509Certificate2)
        {

            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random = new SecureRandom(randomGenerator);

            var kpgen = new RsaKeyPairGenerator();
            kpgen.Init(new KeyGenerationParameters(random, 2048));
            var subjectKeyPair = kpgen.GenerateKeyPair();

            var gen = new X509V3CertificateGenerator();

            X509Name certName;
            if (certificatePolicy.X509NameDictionary == null || !certificatePolicy.X509NameDictionary.Any())
            {
                certName = new X509Name("CN=" + certificatePolicy.CommonName);
            }
            else
            {
                var list = new Dictionary<string, string>();
                AddSubjectNameItem(list, "CN", certificatePolicy.CommonName);
                foreach (var item in certificatePolicy.X509NameDictionary)
                {
                    AddSubjectNameItem(list, item.Key, item.Value);
                }
                certName = new X509Name(GetSubjectNameItemString(list));
            }

            BigInteger serialNo;
            serialNo = BigInteger.ProbablePrime(120, random);

            gen.SetSerialNumber(serialNo);
            gen.SetSubjectDN(certName);
            gen.SetIssuerDN(certName);

            gen.SetNotBefore(DateTime.UtcNow.AddHours(-2)); // go back 2 hours just to be safe
            gen.SetNotAfter(DateTime.UtcNow.AddDays(certificatePolicy.ValidForDays));
            gen.SetSignatureAlgorithm("SHA256WithRSA");
            gen.SetPublicKey(subjectKeyPair.Public);

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

            gen.AddExtension(X509Extensions.KeyUsage.Id,
                true,
                new KeyUsage(KeyUsage.DigitalSignature));

            // handle our key purposes
            if (!certificatePolicy.AllPurposes)
            {
                var purposes = new List<KeyPurposeID>();
                if (certificatePolicy.ServerAuthentication)
                {
                    purposes.Add(KeyPurposeID.IdKPServerAuth);
                }
                if (certificatePolicy.ClientAuthentication)
                {
                    purposes.Add(KeyPurposeID.IdKPClientAuth);
                }
                if (certificatePolicy.CodeSigning)
                {
                    purposes.Add(KeyPurposeID.IdKPCodeSigning);
                }
                if (purposes.Any())
                {
                    gen.AddExtension(
                      X509Extensions.ExtendedKeyUsage.Id,
                      true,
                      new ExtendedKeyUsage(purposes.ToArray()));
                }
            }

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

            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);

            var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded());
            if (seq.Count != 9)
            {
                throw new PemException("Malformed sequence in RSA private key.");
            }

            var rsa = new RsaPrivateKeyStructure(seq);
            RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            // this is exportable to get the bytes of the key to our file system in an encrypted manner
            RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(rsaparams);
            CspParameters cspParameters = new CspParameters();
            cspParameters.KeyContainerName = Guid.NewGuid().ToString();
            RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(2048, cspParameters);
            rsaKey.PersistKeyInCsp = false; // do not persist          
            rsaKey.ImportParameters(rsaParameters);

            var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());
            x509.PrivateKey = rsaKey;

            // this is non-exportable
            CspParameters cspParametersNoExport = new CspParameters();
            cspParametersNoExport.KeyContainerName = Guid.NewGuid().ToString();
            cspParametersNoExport.Flags = CspProviderFlags.UseNonExportableKey;
            RSACryptoServiceProvider rsaKey2 = new RSACryptoServiceProvider(2048, cspParametersNoExport);
            rsaKey2.PersistKeyInCsp = false; // do not persist   
            rsaKey2.ImportParameters(rsaParameters);

            x509Certificate2 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());
            x509Certificate2.PrivateKey = rsaKey2;

            //// Generating Random Numbers
            //var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-()#$%^&@+=!";
            //var rnd = new Random();

            //password = new string(
            //    Enumerable.Repeat(chars, 15)
            //              .Select(s => s[rnd.Next(s.Length)])
            //              .ToArray());

            thumbprint = x509.Thumbprint.ToLower();

            var publicKeyPem = new StringBuilder();
            var utf8WithoutBom = new System.Text.UTF8Encoding(false);
            var publicKeyPemWriter = new PemWriter(new StringWriterWithEncoding(publicKeyPem, utf8WithoutBom));
            publicKeyPemWriter.WriteObject(certificate);
            publicKeyPemWriter.Writer.Flush();
            pemPublicCert = publicKeyPem.ToString();
            pemPublicCert = pemPublicCert.Replace(Environment.NewLine, "\n"); //only use newline and not returns

            pkcs12Data = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pfx);
        }
        public static byte[] GenerateRootCertificate(string subjectName, string password, out string pemValue)
        {

            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random = new SecureRandom(randomGenerator);

            var kpgen = new RsaKeyPairGenerator();
            kpgen.Init(new KeyGenerationParameters(random, 2048)); //new SecureRandom(new CryptoApiRandomGenerator()), 2048));
            var subjectKeyPair = kpgen.GenerateKeyPair();

            var gen = new X509V3CertificateGenerator();

            var certName = new X509Name("CN=" + subjectName);
            BigInteger serialNo = BigInteger.ValueOf(4); //BigInteger.ProbablePrime(120, random);
            gen.SetSerialNumber(serialNo);

            gen.SetSubjectDN(certName);
            gen.SetIssuerDN(certName);

            gen.SetNotAfter(DateTime.Now.AddYears(100));
            gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0)));
            gen.SetSignatureAlgorithm("SHA256WithRSA"); //("MD5WithRSA");
            gen.SetPublicKey(subjectKeyPair.Public);

            //gen.AddExtension(
            //    X509Extensions.SubjectKeyIdentifier,
            //    false,
            //    new SubjectKeyIdentifierStructure(kp.Public)
            //    );

            //gen.AddExtension(
            //    X509Extensions.AuthorityKeyIdentifier.Id,
            //    false,
            //    new AuthorityKeyIdentifier(
            //        SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public),
            //        new GeneralNames(new GeneralName(certName)),
            //        serialNo));

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

            var privateKeyPem = new StringBuilder();
            var privateKeyPemWriter = new PemWriter(new StringWriter(privateKeyPem));

            privateKeyPemWriter.WriteObject(certificate);
            privateKeyPemWriter.WriteObject(subjectKeyPair.Private);
            privateKeyPemWriter.Writer.Flush();
            pemValue = privateKeyPem.ToString();
            System.IO.File.WriteAllText(@"C:\_rootCa.pem", pemValue);

            //var certBytes = DotNetUtilities.ToX509Certificate(certificate).Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs12, password);

            //var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());

            //RSA rsaPriv = DotNetUtilities.ToRSA(subjectKeyPair.Private as RsaPrivateCrtKeyParameters);

            //
            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);
            var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());
            var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded());
            if (seq.Count != 9)
            {
                throw new PemException("malformed sequence in RSA private key");
            }

            var rsa = new RsaPrivateKeyStructure(seq);
            RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            //-------------

            //RsaPrivateCrtKeyParameters rsaparams = (RsaPrivateCrtKeyParameters)subjectKeyPair.Private;
            RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(rsaparams);
            CspParameters cspParameters = new CspParameters();
            cspParameters.KeyContainerName = Guid.NewGuid().ToString(); // "MyKeyContainer";
            RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(2048, cspParameters);
            rsaKey.ImportParameters(rsaParameters);

            // ------------

            x509.PrivateKey = rsaKey; // DotNetUtilities.ToRSA(rsaparams);
            //


            var x509Bytes = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert, password);
            System.IO.File.WriteAllBytes(@"C:\_rootCa.cer", x509Bytes);

            var x509Bytes2 = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pfx, password);
            System.IO.File.WriteAllBytes(@"C:\_rootCa.pfx", x509Bytes2);

            return x509Bytes;
        }
        /// <summary>
        /// Static method used to create a certificate and return as a .net object
        /// </summary>
        public static X509Certificate2 Create(string name, DateTime start, DateTime end, string userPassword, bool addtoStore = false, string exportDirectory = null)
        {
            // generate a key pair using RSA
            var generator = new RsaKeyPairGenerator();
            // keys have to be a minimum of 2048 bits for Azure
            generator.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 2048));
            AsymmetricCipherKeyPair cerKp = generator.GenerateKeyPair();
            // get a copy of the private key
            AsymmetricKeyParameter privateKey = cerKp.Private;

            // create the CN using the name passed in and create a unique serial number for the cert
            var certName = new X509Name("CN=" + name);
            BigInteger serialNo = BigInteger.ProbablePrime(120, new Random());

            // start the generator and set CN/DN and serial number and valid period
            var x509Generator = new X509V3CertificateGenerator();
            x509Generator.SetSerialNumber(serialNo);
            x509Generator.SetSubjectDN(certName);
            x509Generator.SetIssuerDN(certName);
            x509Generator.SetNotBefore(start);
            x509Generator.SetNotAfter(end);
            // add the server authentication key usage
            var keyUsage = new KeyUsage(KeyUsage.KeyEncipherment);
            x509Generator.AddExtension(X509Extensions.KeyUsage, false, keyUsage.ToAsn1Object());
            var extendedKeyUsage = new ExtendedKeyUsage(new[] {KeyPurposeID.IdKPServerAuth});
            x509Generator.AddExtension(X509Extensions.ExtendedKeyUsage, true, extendedKeyUsage.ToAsn1Object());
            // algorithm can only be SHA1 ??
            x509Generator.SetSignatureAlgorithm("sha1WithRSA");

            // Set the key pair
            x509Generator.SetPublicKey(cerKp.Public);
            X509Certificate certificate = x509Generator.Generate(cerKp.Private);

            // export the certificate bytes
            byte[] certStream = DotNetUtilities.ToX509Certificate(certificate).Export(X509ContentType.Pkcs12, userPassword);

            // build the key parameter and the certificate entry
            var keyEntry = new AsymmetricKeyEntry(privateKey);
            var entry = new X509CertificateEntry(certificate);
            // build the PKCS#12 store to encapsulate the certificate
            var builder = new Pkcs12StoreBuilder();
            builder.SetUseDerEncoding(true);
            builder.SetCertAlgorithm(PkcsObjectIdentifiers.Sha1WithRsaEncryption);
            builder.SetKeyAlgorithm(PkcsObjectIdentifiers.Sha1WithRsaEncryption);
            builder.Build();
            // create a memorystream to hold the output
            var stream = new MemoryStream(10000);
            // create the individual store and set two entries for cert and key
            var store = new Pkcs12Store();
            store.SetCertificateEntry("Created by Fluent Management", entry);
            store.SetKeyEntry("Created by Fluent Management", keyEntry, new[] { entry });
            store.Save(stream, userPassword.ToCharArray(), new SecureRandom());

             // Create the equivalent C# representation
            var cert = new X509Certificate2(stream.GetBuffer(), userPassword, X509KeyStorageFlags.Exportable);
            // set up the PEM writer too
            if (exportDirectory != null)
            {
                var textWriter = new StringWriter();
                var pemWriter = new PemWriter(textWriter);
                pemWriter.WriteObject(cerKp.Private, "DESEDE", userPassword.ToCharArray(), new SecureRandom());
                pemWriter.Writer.Flush();
                string privateKeyPem = textWriter.ToString();
                using (var writer = new StreamWriter(Path.Combine(exportDirectory, cert.Thumbprint + ".pem")))
                    {
                        writer.WriteLine(privateKeyPem);
                    }
                // also export the certs - first the .pfx
                byte[] privateKeyBytes = cert.Export(X509ContentType.Pfx, userPassword);
                using (var writer = new FileStream(Path.Combine(exportDirectory, cert.Thumbprint + ".pfx"), FileMode.OpenOrCreate, FileAccess.Write))
                {
                    writer.Write(privateKeyBytes, 0, privateKeyBytes.Length);
                }
                // also export the certs - then the .cer
                byte[] publicKeyBytes = cert.Export(X509ContentType.Cert);
                using (var writer = new FileStream(Path.Combine(exportDirectory, cert.Thumbprint + ".cer"), FileMode.OpenOrCreate, FileAccess.Write))
                {
                    writer.Write(publicKeyBytes, 0, publicKeyBytes.Length);
                }
            }

            // if specified then this add this certificate to the store
            if (addtoStore)
                AddToMyStore(cert);

            return cert;
        }
Exemple #38
0
        private void GenerateKey(string fileName)
        {
            string fileNamePublic = fileName + ".pub";

            if (File.Exists(fileNamePublic) &&
                 ShowMessageBox("Overwrite", "File " + fileNamePublic + " already exists. Overwrite?", MessageBoxButtons.YesNo,
                     MessageBoxIcon.Warning) == DialogResult.No)
            {
                return;
            }

            RsaKeyPairGenerator g = new RsaKeyPairGenerator();
            g.Init(new KeyGenerationParameters(new SecureRandom(), Convert.ToInt32(cbKeyLength.Text, 10)));
            AsymmetricCipherKeyPair pair = g.GenerateKeyPair();

            //PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(pair.Private);
            //byte [] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetDerEncoded();

            SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pair.Public);
            byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();

            //Save private key to filename
            try
            {
                using (StreamWriter file = new StreamWriter(fileName))
                {
                    PemWriter pWrt = new PemWriter(file);
                    pWrt.WriteObject(pair);
                    pWrt.Writer.Close();
                }

                //Save public key to filename
                using (StreamWriter file = new StreamWriter(fileNamePublic))
                {
                    PemWriter pWrt = new PemWriter(file);
                    pWrt.WriteObject(pair.Public);
                    pWrt.Writer.Close();
                }
            }
            catch (Exception ex)
            {
                ShowMessageBox("Key file error.", "Couldn't save key pair:\n" + ex.Message, MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return;
            }


            UpdateSuggestedDns(Convert.ToBase64String(serializedPublicBytes));
            SetDomainKeyPath(fileName);
        }
Exemple #39
0
	public void CommitCryptoStuffToRegistry()
	{
		Org.BouncyCastle.OpenSsl.PemWriter PW;
		MemoryStream MS;
		TextWriter TW;

		if (sHostID == null || RootKey == null || RootCertificate == null
				|| HostKey == null || HostCertificate == null)
			return;

		RegistryKey RKey = Registry.CurrentUser.CreateSubKey("Software\\jPhone\\" + _UniqueDeviceID);
		if (RKey != null)
		{
			RKey.SetValue("HostID", sHostID);

			MS = new MemoryStream();
			TW = new StreamWriter(MS);
			PW = new Org.BouncyCastle.OpenSsl.PemWriter(TW);
			PW.WriteObject(RootKey);
			RKey.SetValue("RootKey", MS.GetBuffer());
			TW.Close();
			MS.Close();

			MS = new MemoryStream();
			TW = new StreamWriter(MS);
			PW = new Org.BouncyCastle.OpenSsl.PemWriter(TW);
			PW.WriteObject(RootCertificate);
			RKey.SetValue("RootCert", MS.GetBuffer());
			TW.Close();
			MS.Close();

			MS = new MemoryStream();
			TW = new StreamWriter(MS);
			PW = new Org.BouncyCastle.OpenSsl.PemWriter(TW);
			PW.WriteObject(HostKey);
			RKey.SetValue("HostKey", MS.GetBuffer());
			TW.Close();
			MS.Close();

			MS = new MemoryStream();
			TW = new StreamWriter(MS);
			PW = new Org.BouncyCastle.OpenSsl.PemWriter(TW);
			PW.WriteObject(HostCertificate);
			RKey.SetValue("HostCert", MS.GetBuffer());
			TW.Close();
			MS.Close();

			RKey.Close();
		}
	}
        public static void GenerateRootCertificate(string subjectName, DateTime expireOnUtc, out string password, out string pemValue, out byte[] cerData, out byte[] pkcs12Data)
        {

            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random = new SecureRandom(randomGenerator);

            var kpgen = new RsaKeyPairGenerator();
            kpgen.Init(new KeyGenerationParameters(random, 2048)); 
            var subjectKeyPair = kpgen.GenerateKeyPair();

            var gen = new X509V3CertificateGenerator();

            var certName = new X509Name("CN=" + subjectName);
            BigInteger serialNo = BigInteger.ProbablePrime(120, random);
            gen.SetSerialNumber(serialNo);

            gen.SetSubjectDN(certName);
            gen.SetIssuerDN(certName);

            gen.SetNotAfter(expireOnUtc);
            gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0)));
            gen.SetSignatureAlgorithm("SHA256WithRSA");
            gen.SetPublicKey(subjectKeyPair.Public);

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

            var privateKeyPem = new StringBuilder();
            var privateKeyPemWriter = new PemWriter(new StringWriter(privateKeyPem));

            privateKeyPemWriter.WriteObject(certificate);
            privateKeyPemWriter.WriteObject(subjectKeyPair.Private);
            privateKeyPemWriter.Writer.Flush();
            pemValue = privateKeyPem.ToString();

            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);
            var x509 = X509CertificateHelper.GetCertificate(certificate.GetEncoded(), null, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable);
            var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded());
            if (seq.Count != 9)
            {
                throw new PemException("Malformed sequence in RSA private key.");
            }

            var rsa = new RsaPrivateKeyStructure(seq);
            RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(rsaparams);
            CspParameters cspParameters = new CspParameters();
            cspParameters.KeyContainerName = Guid.NewGuid().ToString(); // "MyKeyContainer";
            RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(2048, cspParameters);
            rsaKey.ImportParameters(rsaParameters);

            x509.PrivateKey = rsaKey; 

            // Generating Random Numbers
            var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-()#$%^&@+=!";
            var rnd = new Random();

            var result = new string(
                Enumerable.Repeat(chars, 15)
                          .Select(s => s[rnd.Next(s.Length)])
                          .ToArray());
            password = result;

            cerData = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert);
            pkcs12Data = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pfx, password);

        }