예제 #1
1
 /// <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();
 }
예제 #2
0
        public static void SaveToFile(
            X509Certificate newCert,
            AsymmetricCipherKeyPair kp,
            string FilePath,
            string CertAlias,
            string Password)
        {
            var newStore = new Pkcs12Store();

            var certEntry = new X509CertificateEntry(newCert);

            newStore.SetCertificateEntry(
                CertAlias,
                certEntry
                );

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

            using (var certFile = File.Create(FilePath))
            {
                newStore.Save(
                    certFile,
                    Password.ToCharArray(),
                    new SecureRandom(new CryptoApiRandomGenerator())
                    );
            }
        }
예제 #3
0
        // https://social.msdn.microsoft.com/Forums/vstudio/en-US/80ccc76f-bf98-4cda-9583-f651013b24a5/extract-private-key-as-string-from-pfx-file?forum=csharpgeneral
        // One of my collegues actually found the solution and I thought I'd share it.
        // Extract Private Key as String from PFX File
        public static void GetPrivateKey(string pfxLocation, string password)
        {
            // Windows's PFX files are just renamed PKCS#12 files,

            // Load your certificate from file
            System.Security.Cryptography.X509Certificates.X509Certificate2 certificate =
                new System.Security.Cryptography.X509Certificates.X509Certificate2(pfxLocation, password
                                                                                   , System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable
                                                                                   | System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.PersistKeySet);


            // Private Key
            if (certificate.HasPrivateKey)
            {
                throw new System.IO.InvalidDataException("no private key in pfx file.");
            }

            System.Security.Cryptography.RSACryptoServiceProvider rsa = (System.Security.Cryptography.RSACryptoServiceProvider)certificate.PrivateKey;
            System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
            System.IO.TextWriter   streamWriter = new System.IO.StreamWriter(memoryStream);


            Org.BouncyCastle.OpenSsl.PemWriter pemWriter            = new Org.BouncyCastle.OpenSsl.PemWriter(streamWriter);
            Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keyPair = Org.BouncyCastle.Security.DotNetUtilities.GetRsaKeyPair(rsa);
            pemWriter.WriteObject(keyPair.Private);
            streamWriter.Flush();
            string output          = System.Text.Encoding.ASCII.GetString(memoryStream.GetBuffer()).Trim();
            int    index_of_footer = output.IndexOf("-----END RSA PRIVATE KEY-----");

            memoryStream.Close();
            streamWriter.Close();
            string PrivKey = output.Substring(0, index_of_footer + 29);
        }
예제 #4
0
        public static byte[] encodeUserKeyPairPrivate(AsymmetricCipherKeyPair userKey)
        {
            PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(userKey.Private);
            byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetDerEncoded();

            return serializedPrivateBytes;
        }
예제 #5
0
        public static byte[] encodeUserKeyPairPublic(AsymmetricCipherKeyPair userKey)
        {
            SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(userKey.Public);
            byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();

            return serializedPublicBytes;
        }
예제 #6
0
		public static X509Certificate MakeCertificate(AsymmetricCipherKeyPair _subKP,
			string _subDN, AsymmetricCipherKeyPair _issKP, string _issDN, string algorithm, bool _ca)
		{
			AsymmetricKeyParameter _subPub = _subKP.Public;
			AsymmetricKeyParameter _issPriv = _issKP.Private;
			AsymmetricKeyParameter _issPub = _issKP.Public;

			X509V3CertificateGenerator _v3CertGen = new X509V3CertificateGenerator();

			_v3CertGen.Reset();
			_v3CertGen.SetSerialNumber(allocateSerialNumber());
			_v3CertGen.SetIssuerDN(new X509Name(_issDN));
			_v3CertGen.SetNotBefore(DateTime.UtcNow);
			_v3CertGen.SetNotAfter(DateTime.UtcNow.AddDays(100));
			_v3CertGen.SetSubjectDN(new X509Name(_subDN));
			_v3CertGen.SetPublicKey(_subPub);
			_v3CertGen.SetSignatureAlgorithm(algorithm);

			_v3CertGen.AddExtension(X509Extensions.SubjectKeyIdentifier, false,
				createSubjectKeyId(_subPub));

			_v3CertGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false,
				createAuthorityKeyId(_issPub));

			_v3CertGen.AddExtension(X509Extensions.BasicConstraints, false,
				new BasicConstraints(_ca));

			X509Certificate _cert = _v3CertGen.Generate(_issPriv);

			_cert.CheckValidity(DateTime.UtcNow);
			_cert.Verify(_issPub);

			return _cert;
		}
예제 #7
0
		public PgpKeyPair(
            PublicKeyAlgorithmTag	algorithm,
            AsymmetricCipherKeyPair	keyPair,
            DateTime				time)
			: this(algorithm, keyPair.Public, keyPair.Private, time)
        {
        }
예제 #8
0
        /// <summary>
        /// Generate a cert/key pair
        /// </summary>
        private void GenerateCertKeyPair()
        {
            // Generate RSA key pair
            RsaKeyPairGenerator r = new RsaKeyPairGenerator();
            r.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
            keyPair = r.GenerateKeyPair();

            // Generate the X509 certificate
            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
            X509Name dnName = new X509Name("CN=NVIDIA GameStream Client");

            certGen.SetSerialNumber(BigInteger.ValueOf(DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond));
            certGen.SetSubjectDN(dnName);
            certGen.SetIssuerDN(dnName); // use the same
            // Expires in 20 years
            certGen.SetNotBefore(DateTime.Now);
            certGen.SetNotAfter(DateTime.Now.AddYears(20));
            certGen.SetPublicKey(keyPair.Public);
            certGen.SetSignatureAlgorithm("SHA1withRSA");

            try
            {
                cert = certGen.Generate(keyPair.Private);

            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.StackTrace);
            }

            Task.Run(async () => await SaveCertKeyPair()).Wait(); 
        }
예제 #9
0
        static void test()
        {
            RsaKeyPairGenerator rsaKeyPairGnr_s = new RsaKeyPairGenerator();

            rsaKeyPairGnr_s.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(new SecureRandom(), 32));
            Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keyPair_s = rsaKeyPairGnr_s.GenerateKeyPair();

            RsaKeyParameters pubKey = (RsaKeyParameters)keyPair_s.Public;
            RsaKeyParameters prKey  = (RsaKeyParameters)keyPair_s.Private;

            IAsymmetricBlockCipher cipher = new RsaEngine();

            cipher.Init(true, prKey);
            byte[] plain_byte = BitConverter.GetBytes(10);

            byte[] enc = cipher.ProcessBlock(plain_byte, 0, plain_byte.Length);

            Org.BouncyCastle.Math.BigInteger test = new Org.BouncyCastle.Math.BigInteger(enc);
            Console.WriteLine(test);

            test = test.Multiply(new Org.BouncyCastle.Math.BigInteger(BitConverter.GetBytes(2)));

            test = test.Mod(prKey.Modulus);

            Console.WriteLine(test);

            byte[] new_enc = test.ToByteArray();

            cipher.Init(false, pubKey);

            byte[] dec = cipher.ProcessBlock(new_enc, 0, new_enc.Length);

            Console.WriteLine(BitConverter.ToInt32(dec));
        }
예제 #10
0
 public static byte[] GetObsoleteSharedSecret(AsymmetricCipherKeyPair localKeyWithPrivate, byte[] remotePublicKeyDerEncoded)
 {
     var remotePublicKey = PublicKeyFactory.CreateKey(remotePublicKeyDerEncoded);
     var agreement = new ECDHBasicAgreement();
     agreement.Init(localKeyWithPrivate.Private);
     return agreement.CalculateAgreement(remotePublicKey).ToByteArray();
 }
		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);
		}
예제 #12
0
 /// <summary>
 /// Public constructor for a Pkcs certificate, takes in values to describe it's state.
 /// </summary>
 /// <param name="password">The value used to secure (encrypt) the private key with the certificate</param>
 /// <param name="keypair">An object used for manipulating/accessing the public and private key of a certificate</param>
 /// <param name="cert">An easy to manipulate version of an X509 certificate</param>
 /// <param name="store">A store of Pkcs12 certificates used to store and manipulate certificat chains and key associations</param>
 public PkcsCertificate(string password ,AsymmetricCipherKeyPair keypair, Org.BouncyCastle.X509.X509Certificate cert, Pkcs12Store store)
 {
     this.Password = password;
     this.Keypair = keypair;
     this.X509Certificate = cert;
     this.PkcsStore = store;
     // this is not the best place to do this
 }
예제 #13
0
파일: DkimTests.cs 프로젝트: dcga/MimeKit
		static DkimTests ()
		{
			using (var stream = new StreamReader (Path.Combine ("..", "..", "TestData", "dkim", "example.pem"))) {
				var reader = new PemReader (stream);

				DkimKeys = reader.ReadObject () as AsymmetricCipherKeyPair;
			}
		}
예제 #14
0
 private static byte[] ExportCertificate(X509Certificate certificate, AsymmetricCipherKeyPair subjectKeyPair, TCertificateFormat certificateFormat)
 {
     byte[] result = null;
     switch (certificateFormat)
     {
         case TCertificateFormat.NotSet:
             break;
         case TCertificateFormat.PEM:
             using (MemoryStream stream = new MemoryStream())
             {
                 using (StreamWriter writer = new StreamWriter(stream))
                 {
                     Org.BouncyCastle.Utilities.IO.Pem.PemWriter pemWriter = new Org.BouncyCastle.Utilities.IO.Pem.PemWriter(writer);
                     if (subjectKeyPair.Private is ECKeyParameters)
                     {
                         ECPrivateKeyParameters priv = (ECPrivateKeyParameters)subjectKeyPair.Private;
                         ECDomainParameters dp = priv.Parameters;
                         int orderBitLength = dp.N.BitLength;
                         Org.BouncyCastle.Asn1.Sec.ECPrivateKeyStructure ec;
                         Org.BouncyCastle.Asn1.X9.X962Parameters x962;
                         if (priv.PublicKeyParamSet == null)
                         {
                             Org.BouncyCastle.Asn1.X9.X9ECParameters ecP = new Org.BouncyCastle.Asn1.X9.X9ECParameters(dp.Curve, dp.G, dp.N, dp.H, dp.GetSeed());
                             x962 = new Org.BouncyCastle.Asn1.X9.X962Parameters(ecP);
                         }
                         else
                         {
                             x962 = new Org.BouncyCastle.Asn1.X9.X962Parameters(priv.PublicKeyParamSet);
                         }
                         ec = new Org.BouncyCastle.Asn1.Sec.ECPrivateKeyStructure(orderBitLength, priv.D, SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public).PublicKeyData, x962);
                         pemWriter.WriteObject(new Org.BouncyCastle.Utilities.IO.Pem.PemObject("EC PRIVATE KEY", ec.GetEncoded()));
                     }
                     else
                     {
                         pemWriter.WriteObject(new Org.BouncyCastle.OpenSsl.MiscPemGenerator(subjectKeyPair.Private));
                     }
                     pemWriter.WriteObject(new Org.BouncyCastle.OpenSsl.MiscPemGenerator(subjectKeyPair.Public));
                     pemWriter.WriteObject(new Org.BouncyCastle.OpenSsl.MiscPemGenerator(certificate));
                     writer.Flush();
                     result = stream.ToArray();
                 }
             }
             break;
         case TCertificateFormat.PFX:
             //Asn1Sequence asn1Sequence = Asn1Sequence.GetInstance(Asn1Object.FromByteArray(certificate.GetEncoded()));
             //asn1Sequence.GetObjects
             //Org.BouncyCastle.Asn1.Pkcs.Pfx pfx = new Org.BouncyCastle.Asn1.Pkcs.Pfx();
             //Org.BouncyCastle.Asn1.Pkcs.PrivateKeyInfo info = Org.BouncyCastle.Pkcs.PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);
             //result = pfx.GetEncoded(Asn1Encodable.Der);
             break;
         case TCertificateFormat.CER:
             result = certificate.GetEncoded();
             break;
         default:
             break;
     }
     return result;
 }
예제 #15
0
파일: Key.cs 프로젝트: bitdiff/secular
        public Key(int strength)
        {
            var generator = new RsaKeyPairGenerator();
            generator.Init(new KeyGenerationParameters(new SecureRandom(), strength));
            _keyPair = generator.GenerateKeyPair();
            _rsaKey = _keyPair.Private as RsaPrivateCrtKeyParameters;

            PublicKey = new PublicKey(_keyPair.Public as RsaKeyParameters);
        }
예제 #16
0
 // This returns a
 public static string GetPrivateKey(AsymmetricCipherKeyPair keyPair)
 {
     var dhPrivateKeyParameters = keyPair.Private as DHPrivateKeyParameters;
     if (dhPrivateKeyParameters != null)
     {
         return dhPrivateKeyParameters.X.ToString();
     }
     throw new NullReferenceException("The key pair provided is not a valid DH keypair.");
 }
예제 #17
0
        public DHProvider(DHParameters parameters)
        {
            _parameters = parameters;

            IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("DH");
            KeyGenerationParameters kgp = new DHKeyGenerationParameters(new SecureRandom(), _parameters);

            keyGen.Init(kgp);
            _kp = keyGen.GenerateKeyPair();
        }
예제 #18
0
 public static byte[] GetSharedSecret(AsymmetricCipherKeyPair localKeyWithPrivate, byte[] remotePublicKeyDerEncoded)
 {
     var remotePublicKey = PublicKeyFactory.CreateKey(remotePublicKeyDerEncoded);
     var agreement = new ECDHBasicAgreement();
     agreement.Init(localKeyWithPrivate.Private);
     using (var sha = SHA256.Create()) {
         // CalculateAgreement returns a BigInteger, whose length is variable, and bits are not whitened.
         // So hash it.
         return sha.ComputeHash(agreement.CalculateAgreement(remotePublicKey).ToByteArray());
     }
 }
예제 #19
0
        public ServerAuthority(DHParameters parameters)
        {
            this.parameters = parameters;

            IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("DH");
            KeyGenerationParameters kgp = new DHKeyGenerationParameters(new SecureRandom(), parameters);

            keyGen.Init(kgp);
            kp = keyGen.GenerateKeyPair();
            agreement = AgreementUtilities.GetBasicAgreement("DH");
            agreement.Init(kp.Private);
        }
        static void gen_keys()
        {
            var key_variable = Encoding.ASCII.GetBytes("test_pro");

            RsaKeyPairGenerator rsaKeyPairGnr_s = new RsaKeyPairGenerator();

            rsaKeyPairGnr_s.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(new SecureRandom(key_variable), 512));
            Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keyPair_s = rsaKeyPairGnr_s.GenerateKeyPair();

            Pp = (RsaKeyParameters)keyPair_s.Public;
            Sp = (RsaKeyParameters)keyPair_s.Private;
        }
예제 #21
0
 public Account()
 {
     var namedCurve = NistNamedCurves.GetByName("P-256");
     var ecdomp = new ECDomainParameters(namedCurve.Curve, namedCurve.G, namedCurve.N);
     var srnd = new SecureRandom();
     var eckeygenparams = new ECKeyGenerationParameters(ecdomp, srnd);
     var g = new ECKeyPairGenerator("ECDSA");
     g.Init(eckeygenparams);
     keyPair = g.GenerateKeyPair();
     address = generateAddress(keyPair.Public);
     this.Label = "(no label)";
 }
        public static RsaKeyParameters req_ver_key()
        {
            var key_variable = Encoding.ASCII.GetBytes("test_ver");

            RsaKeyPairGenerator rsaKeyPairGnr_s = new RsaKeyPairGenerator();

            rsaKeyPairGnr_s.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(new SecureRandom(key_variable), 512));
            Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keyPair_s = rsaKeyPairGnr_s.GenerateKeyPair();

            RsaKeyParameters key = (RsaKeyParameters)keyPair_s.Public;

            return(key);
        }
예제 #23
0
 /// <summary>
 /// Add the Authority Key Identifier. According to http://www.alvestrand.no/objectid/2.5.29.35.html, this
 /// identifies the public key to be used to verify the signature on this certificate.
 /// In a certificate chain, this corresponds to the "Subject Key Identifier" on the *issuer* certificate.
 /// The Bouncy Castle documentation, at http://www.bouncycastle.org/wiki/display/JA1/X.509+Public+Key+Certificate+and+Certification+Request+Generation,
 /// shows how to create this from the issuing certificate. Since we're creating a self-signed certificate, we have to do this slightly differently.
 /// </summary>
 /// <param name="certificateGenerator"></param>
 /// <param name="issuerDN"></param>
 /// <param name="issuerKeyPair"></param>
 /// <param name="issuerSerialNumber"></param>
 private static void AddAuthorityKeyIdentifier(X509V3CertificateGenerator certificateGenerator,
                                               X509Name issuerDN,
                                               AsymmetricCipherKeyPair issuerKeyPair,
                                               BigInteger issuerSerialNumber)
 {
     var authorityKeyIdentifierExtension =
         new AuthorityKeyIdentifier(
             SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerKeyPair.Public),
             new GeneralNames(new GeneralName(issuerDN)),
             issuerSerialNumber);
     certificateGenerator.AddExtension(
         X509Extensions.AuthorityKeyIdentifier.Id, false, authorityKeyIdentifierExtension);
 }
        public static RsaKeyParameters[] req_keys(int n)
        {
            RsaKeyParameters[] keys = new RsaKeyParameters[n];
            for (int i = 0; i < n; ++i)
            {
                RsaKeyPairGenerator rsaKeyPairGnr_s = new RsaKeyPairGenerator();
                rsaKeyPairGnr_s.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(new SecureRandom(), 512));
                Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keyPair_s = rsaKeyPairGnr_s.GenerateKeyPair();

                keys[i] = (RsaKeyParameters)keyPair_s.Public;
            }
            return(keys);
        }
예제 #25
0
            GenerateCertificate(string subjectName, out AsymmetricCipherKeyPair kp)
        {
            var kpgen = new RsaKeyPairGenerator();

            // certificate strength 1024 bits
            kpgen.Init(new KeyGenerationParameters(
                  new SecureRandom(new CryptoApiRandomGenerator()), 1024));

            kp = kpgen.GenerateKeyPair();

            var gen = new X509V3CertificateGenerator();

            var certName = new X509Name("CN=" + subjectName);
            var serialNo = BigInteger.ProbablePrime(120, new 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("SHA1withRSA");
            gen.SetPublicKey(kp.Public);

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

            /* 
             1.3.6.1.5.5.7.3.1 - id_kp_serverAuth 
             1.3.6.1.5.5.7.3.2 - id_kp_clientAuth 
             1.3.6.1.5.5.7.3.3 - id_kp_codeSigning 
             1.3.6.1.5.5.7.3.4 - id_kp_emailProtection 
             1.3.6.1.5.5.7.3.5 - id-kp-ipsecEndSystem 
             1.3.6.1.5.5.7.3.6 - id-kp-ipsecTunnel 
             1.3.6.1.5.5.7.3.7 - id-kp-ipsecUser 
             1.3.6.1.5.5.7.3.8 - id_kp_timeStamping 
             1.3.6.1.5.5.7.3.9 - OCSPSigning
             */
            gen.AddExtension(
                X509Extensions.ExtendedKeyUsage.Id,
                false,
                new ExtendedKeyUsage(new[] { KeyPurposeID.IdKPServerAuth }));

            var newCert = gen.Generate(kp.Private);

            return newCert;
        }
예제 #26
0
        /// <summary>
        /// Zertifikat mit privatem Schlüssel verknüpfen. (BouncyCastle-Teil)
        /// </summary>
        /// <param name="bcCert">Zertifikat</param>
        /// <param name="rsaKeyPair">Private Schlüssel</param>
        /// <param name="keyPwd">Passwort mit dem das Zertifikat verschlüsselt werden soll.</param>
        /// <returns></returns>
        private static byte[] LinkPrivateKeyToCert(
            Org.BouncyCastle.X509.X509Certificate bcCert,
            Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair rsaKeyPair,
            System.Security.SecureString keyPwd)
        {
            var pkcs12store = new Org.BouncyCastle.Pkcs.Pkcs12StoreBuilder().Build();

            pkcs12store.SetKeyEntry(string.Empty,
                                    new Org.BouncyCastle.Pkcs.AsymmetricKeyEntry(rsaKeyPair.Private),
                                    new[] { new Org.BouncyCastle.Pkcs.X509CertificateEntry(bcCert) });
            var pkcs12data = new System.IO.MemoryStream();

            pkcs12store.Save(pkcs12data, keyPwd.ToUnencryptedString().ToCharArray(), new Org.BouncyCastle.Security.SecureRandom(new CryptoApiRandomGenerator()));
            return(pkcs12data.ToArray());
        }
예제 #27
0
		static DkimTests ()
		{
			using (var stream = new StreamReader (Path.Combine ("..", "..", "TestData", "dkim", "example.pem"))) {
				var reader = new PemReader (stream);

				DkimKeys = reader.ReadObject () as AsymmetricCipherKeyPair;
			}

			// Note: you can use http://dkimcore.org/tools/dkimrecordcheck.html to get public keys manually
			using (var stream = new StreamReader (Path.Combine ("..", "..", "TestData", "dkim", "gmail.pub"))) {
				var reader = new PemReader (stream);

				GMailDkimPublicKey = reader.ReadObject () as AsymmetricKeyParameter;
			}
		}
예제 #28
0
		public static X509Certificate GenerateRootCert(
			AsymmetricCipherKeyPair pair)
		{
			X509V1CertificateGenerator  certGen = new X509V1CertificateGenerator();

			certGen.SetSerialNumber(BigInteger.One);
			certGen.SetIssuerDN(new X509Name("CN=Test CA Certificate"));
			certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
			certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
			certGen.SetSubjectDN(new X509Name("CN=Test CA Certificate"));
			certGen.SetPublicKey(pair.Public);
			certGen.SetSignatureAlgorithm("SHA256WithRSAEncryption");

			return certGen.Generate(pair.Private);
		}
예제 #29
0
        public static string Crypt(string input)
        {
            RsaKeyParameters parameters;
            AsymmetricCipherKeyPair keyPair;

            using (var reader = File.OpenText(@"publickey.pem")) // file containing RSA PKCS1 private key
                parameters = (RsaKeyParameters)new PemReader(reader).ReadObject();

            keyPair = new AsymmetricCipherKeyPair(parameters, new AsymmetricKeyParameter(true));

            var encryptEngine = new Pkcs1Encoding(new RsaEngine());
            encryptEngine.Init(true, keyPair.Public);

            byte[] utf = Encoding.UTF8.GetBytes(input);
            return Convert.ToBase64String(encryptEngine.ProcessBlock(utf, 0, utf.Length));
        }
예제 #30
0
    public bool doLoadWallet(string thisFile)
    {
        string theWalletJSON = File.ReadAllText(thisFile);
        Console.Out.WriteLine(theWalletJSON);
        Wallet = JsonConvert.DeserializeObject<Dictionary<string, string>>(theWalletJSON);
        Byte[] bKey = Convert.FromBase64String(Wallet["private_key"]);

        // much like java - the built in crypto doesn't work and looks like it was written by and intern
        // you MUST use bouncycastle - dont even try to use the microsoft lib
        String thePEM = Wallet["pem"];
        var reader = new StringReader(thePEM);
        PemReader pr = new PemReader(reader);
        keyPair = (AsymmetricCipherKeyPair)pr.ReadObject();

        return true;
    }
예제 #31
0
파일: Klient.cs 프로젝트: kosa0323/PKRY
        public void WczytajPoczatkoweParametry()
        {
            //Wczytywanie klucza prywatnego Sprzedającego
            readerKluczPrywatny = new StreamReader("KluczPrywatnyKlienta.pem");
            pemReaderKluczPrywatny = new PemReader(readerKluczPrywatny);
            keyPairPriv = (AsymmetricCipherKeyPair)pemReaderKluczPrywatny.ReadObject();
            kluczPrywatnyKlienta = keyPairPriv.Private;

            //Wczytywanie klucza publicznego bramy przeznaczonego tylko dla klienta
            readerKluczPublicznyBramyTylkoDlaKlienta = new StreamReader("KluczPublicznyBramyTylkoDlaKlienta.pem");
            pemReaderkluczPublicznyBramyTylkoDlaKlienta = new PemReader(readerKluczPublicznyBramyTylkoDlaKlienta);
            kluczPublicznyBramyTylkoDlaKlienta = (AsymmetricKeyParameter)pemReaderkluczPublicznyBramyTylkoDlaKlienta.ReadObject();

            //Wczytywanie certyfikatu Klienta
            sciezkaCertyfikatuKlienta = "CertyfikatKlienta.crt";
            certyfikatKlienta = new X509Certificate2(sciezkaCertyfikatuKlienta);
        }
예제 #32
0
        public static byte[] Init()
        {
            AsymmetricCipherKeyPair keyPair = null;

            string path = "proxy/session-key";
            try
            {
                AsymmetricKeyParameter keyPub = PublicKeyFactory.CreateKey(File.ReadAllBytes(path + ".pub"));
                AsymmetricKeyParameter KeyPriv = PrivateKeyFactory.CreateKey(File.ReadAllBytes(path + ".priv"));
                keyPair = new AsymmetricCipherKeyPair(keyPub, KeyPriv);
                Debug.WriteLine("Loaded session.key");
            } catch (Exception e)
            {
                Log.WriteServer(e);

                Debug.WriteLine("Generating session.key...");
                var generator = new RsaKeyPairGenerator();
                generator.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
                keyPair = generator.GenerateKeyPair();
                Debug.WriteLine("Generated, saving...");

                SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public);
                byte[] bytePub = publicKeyInfo.ToAsn1Object().GetDerEncoded();

                Directory.CreateDirectory(Path.GetDirectoryName(path));
                File.WriteAllBytes(path + ".pub", bytePub);

                PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private);                        
                byte[] bytePriv = privateKeyInfo.ToAsn1Object().GetDerEncoded();
                File.WriteAllBytes(path + ".priv", bytePriv);

                Debug.WriteLine("Saved session.key");

            }

            //Old method
            /*var generator = new RsaKeyPairGenerator();
            generator.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
            var keyPair = generator.GenerateKeyPair();
            */

            keyParameters = (RsaKeyParameters)keyPair.Private;
            SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public);
            return info.GetEncoded();
        }
예제 #33
0
        static void Main(string[] args)
        {
            byte[][] X   = new byte[11][];
            Random   rnd = new Random();

            for (int i = 0; i < 11; ++i)
            {
                UTF8Encoding utf8enc = new UTF8Encoding();
                X[i] = utf8enc.GetBytes(rnd.Next().ToString());
            }

            RsaKeyParameters[] P = new RsaKeyParameters[11];

            for (int i = 0; i < 10; ++i)
            {
                RsaKeyPairGenerator rsaKeyPairGnr = new RsaKeyPairGenerator();
                rsaKeyPairGnr.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(new SecureRandom(), 512));
                Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keyPair = rsaKeyPairGnr.GenerateKeyPair();

                RsaKeyParameters       publicKey = (RsaKeyParameters)keyPair.Public;
                IAsymmetricBlockCipher cipher    = new RsaEngine();

                P[i + 1] = publicKey;
            }

            RsaKeyPairGenerator rsaKeyPairGnr_s = new RsaKeyPairGenerator();

            rsaKeyPairGnr_s.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(new SecureRandom(), 512));
            Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keyPair_s = rsaKeyPairGnr_s.GenerateKeyPair();

            P[0] = (RsaKeyParameters)keyPair_s.Public;
            RsaKeyParameters Ks = (RsaKeyParameters)keyPair_s.Private;

            string m = "Hello!!";

            byte[] v = ring_sign(P, m, Ks, X);

            Console.WriteLine("v: " + ByteArrayToString(v));
            Console.WriteLine();

            ring_verify(P, v, X, m);
        }
예제 #34
0
        static void gen_keypair()
        {
            key = KeyGenerator.GenerateKey(polynomsCount * 16);
            var byte_key = KeyGenerator.GenerateDoubleBytesKey(key);
            var hexKey   = KeyGenerator.GetHexKey(byte_key);

            var key_variable = Encoding.ASCII.GetBytes(hexKey);

            RsaKeyPairGenerator rsaKeyPairGnr = new RsaKeyPairGenerator();

            rsaKeyPairGnr.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(new SecureRandom(key_variable), 512));
            Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keyPair = rsaKeyPairGnr.GenerateKeyPair();


            P = (RsaKeyParameters)keyPair.Public;
            S = (RsaKeyParameters)keyPair.Private;


            print_key(hexKey);
        }
        /// <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());
                }
            }
        }
예제 #36
0
        /// <summary>
        /// Create ECDSA and generates new key pair
        /// </summary>
        /// <param name="type">0 or 1 (1 faster)</param>
        /// <param name="forSign">if created for signing, otherwise for verifying</param>
        public ECDSAWrapper(int type, bool forSign)
        {
            try
            {
                this.initCurveandParams(type);

                SecureRandom random = new SecureRandom();
                ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(this.parameters, random);
                ECKeyPairGenerator pGen = new ECKeyPairGenerator();
                pGen.Init(genParam);
                this.pair = pGen.GenerateKeyPair();

                if (forSign)
                    this.ecdsa.Init(true, new ParametersWithRandom(this.pair.Private, random));
                else
                    this.ecdsa.Init(false, this.pair.Public);
            }
            catch (Exception ex)
            {
                throw new Exception("Error while creating ECDSA with new key pair", ex);
            }
        }
		private static void ExportKeyPair(
            Stream					secretOut,
            Stream					publicOut,
            AsymmetricCipherKeyPair	dsaKp,
            AsymmetricCipherKeyPair	elgKp,
            string					identity,
            char[]					passPhrase,
            bool					armor)
        {
            if (armor)
            {
                secretOut = new ArmoredOutputStream(secretOut);
            }

			PgpKeyPair dsaKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.Dsa, dsaKp, DateTime.UtcNow);
            PgpKeyPair elgKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.ElGamalEncrypt, elgKp, DateTime.UtcNow);

			PgpKeyRingGenerator keyRingGen = new PgpKeyRingGenerator(PgpSignature.PositiveCertification, dsaKeyPair,
				identity, SymmetricKeyAlgorithmTag.Aes256, passPhrase, true, null, null, new SecureRandom());

			keyRingGen.AddSubKey(elgKeyPair);

			keyRingGen.GenerateSecretKeyRing().Encode(secretOut);

			if (armor)
            {
				secretOut.Close();
				publicOut = new ArmoredOutputStream(publicOut);
            }

			keyRingGen.GeneratePublicKeyRing().Encode(publicOut);

			if (armor)
			{
				publicOut.Close();
			}
        }
예제 #38
0
        public static byte[] CreatePKCS12KeyStoreWithPublicPrivateKeyPair(AsymmetricCipherKeyPair keyPair, string passphrase)
        {
            var keyContainerName = new Guid().ToString();
            var x509V3CertificateGenerator = new X509V3CertificateGenerator();

            // The fields that Thali cares about
            x509V3CertificateGenerator.SetSignatureAlgorithm(SignerAlgorithm);
            x509V3CertificateGenerator.SetPublicKey(keyPair.Public);

            // To avoid getting an InvalidOperationExceptoin when calling generate below we have to
            // specify a certain number of mandatory fields as explained in http://blog.differentpla.net/post/53
            // We don't actually care about these fields but Bouncy Castle does
            var serialNumber = BigInteger.ProbablePrime(120, new Random());
            x509V3CertificateGenerator.SetSerialNumber(serialNumber);
            x509V3CertificateGenerator.SetSubjectDN(X500Name);
            x509V3CertificateGenerator.SetIssuerDN(X500Name);
            x509V3CertificateGenerator.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(24, 0, 0)));
            x509V3CertificateGenerator.SetNotAfter(DateTime.Now.AddDays(ExpirationPeriodForCertsInDays));

            var bouncyCastleX509Cert = x509V3CertificateGenerator.Generate(keyPair.Private);
            try
            {
                var msX509Cert = new X509Certificate2(DotNetUtilities.ToX509Certificate(bouncyCastleX509Cert))
                {
                    PrivateKey = ToRSA((RsaPrivateCrtKeyParameters)keyPair.Private, keyContainerName)
                };
                var pkcs12Store = msX509Cert.Export(X509ContentType.Pkcs12, passphrase);
                return pkcs12Store;
            }
            finally
            {
                var cspParameters = new CspParameters { KeyContainerName = keyContainerName };
                var rsaCryptoServiceProvider = new RSACryptoServiceProvider(cspParameters) { PersistKeyInCsp = false };
                rsaCryptoServiceProvider.Clear();
            }
        }
예제 #39
0
        public static void ring_authenticate(SslStream sslStream)
        {
            byte[][] X   = new byte[11][];
            Random   rnd = new Random();

            for (int i = 0; i < 11; ++i)
            {
                UTF8Encoding utf8enc = new UTF8Encoding();
                X[i] = utf8enc.GetBytes(rnd.Next().ToString());
            }

            RsaKeyParameters[] P = new RsaKeyParameters[11];

            for (int i = 0; i < 10; ++i)
            {
                RsaKeyPairGenerator rsaKeyPairGnr = new RsaKeyPairGenerator();
                rsaKeyPairGnr.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(new SecureRandom(), 512));
                Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keyPair = rsaKeyPairGnr.GenerateKeyPair();

                RsaKeyParameters       publicKey = (RsaKeyParameters)keyPair.Public;
                IAsymmetricBlockCipher cipher    = new RsaEngine();

                P[i + 1] = publicKey;
            }

            RsaKeyPairGenerator rsaKeyPairGnr_s = new RsaKeyPairGenerator();

            rsaKeyPairGnr_s.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(new SecureRandom(), 512));
            Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keyPair_s = rsaKeyPairGnr_s.GenerateKeyPair();

            P[0] = (RsaKeyParameters)keyPair_s.Public;
            RsaKeyParameters Ks = (RsaKeyParameters)keyPair_s.Private;

            string m = "Hello!!";

            byte[] v = ring_sign(P, m, Ks, X);

            Console.WriteLine("v: " + ByteArrayToString(v));
            Console.WriteLine();

            String P_str = "";

            for (int i = 0; i < 11; ++i)
            {
                byte[] publicKeyDer = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(P[i]).GetDerEncoded();
                P_str = P_str + Convert.ToBase64String(publicKeyDer) + "|";
            }

            String X_str = "";

            for (int i = 0; i < 11; ++i)
            {
                X_str = X_str + Encoding.ASCII.GetString(X[i]) + "|";
            }

            Console.WriteLine(P_str);
            Console.WriteLine(X_str);

            byte[] data = Encoding.UTF8.GetBytes(P_str);
            sslStream.Write(data);

            sslStream.Flush();

            data = Encoding.UTF8.GetBytes(X_str);
            sslStream.Write(data);

            sslStream.Flush();

            TCPCommunication.send_message_tcp(sslStream, m);


            sslStream.Write(v);
            sslStream.Flush();
        }
        static void Main(string[] args)
        {
            n = Int32.Parse(args[0]);
            try
            {
                byte[][] X   = new byte[n + 1][];
                string[] X0  = new string[n + 1];
                Random   rnd = new Random();

                for (int i = 0; i < n + 1; ++i)
                {
                    UTF8Encoding utf8enc = new UTF8Encoding();
                    X0[i] = rnd.Next().ToString();
                    X[i]  = utf8enc.GetBytes(X0[i]);
                }

                RsaKeyParameters[] P = new RsaKeyParameters[n + 1];

                for (int i = 0; i < n; ++i)
                {
                    RsaKeyPairGenerator rsaKeyPairGnr = new RsaKeyPairGenerator();
                    rsaKeyPairGnr.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(new SecureRandom(), 512));
                    Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keyPair = rsaKeyPairGnr.GenerateKeyPair();

                    RsaKeyParameters       publicKey = (RsaKeyParameters)keyPair.Public;
                    IAsymmetricBlockCipher cipher    = new RsaEngine();

                    P[i + 1] = publicKey;
                }

                RsaKeyPairGenerator rsaKeyPairGnr_s = new RsaKeyPairGenerator();
                rsaKeyPairGnr_s.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(new SecureRandom(), 512));
                Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keyPair_s = rsaKeyPairGnr_s.GenerateKeyPair();

                P[0] = (RsaKeyParameters)keyPair_s.Public;
                RsaKeyParameters Ks = (RsaKeyParameters)keyPair_s.Private;


                string server = "127.0.0.1";

                Int32     port   = 13000;
                TcpClient client = new TcpClient(server, port);


                //Time start

                DateTime now = DateTime.Now;
                Console.WriteLine("Strat Second: {0}", now.Millisecond);


                NetworkStream stream = client.GetStream();

                byte[] bytes;
                string response;

                bytes = new byte[64];
                stream.Read(bytes, 0, bytes.Length);
                response = System.Text.Encoding.ASCII.GetString(bytes, 0, bytes.Length);
                string N = response;

                string m = N;

                byte[] v = ring_sign(P, m, Ks, X);

                stream.Write(v);
                Console.WriteLine(v.Length);

                string x = "";
                for (int i = 0; i < n + 1; ++i)
                {
                    x += P[i].Exponent + "|";
                }

                string M = "";
                for (int i = 0; i < n + 1; ++i)
                {
                    M += P[i].Modulus + "|";
                }

                string X0_str = "";
                for (int i = 0; i < n + 1; ++i)
                {
                    X0_str += X0[i] + "|";
                }


                bytes = Encoding.UTF8.GetBytes(x + M + X0_str);
                stream.Write(bytes);

                stream.Flush();



                // Close everything.
                stream.Close();
                client.Close();
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("ArgumentNullException: {0}", e);
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }
        }
예제 #41
0
        // http://stackoverflow.com/questions/36942094/how-can-i-generate-a-self-signed-cert-without-using-obsolete-bouncycastle-1-7-0
        public static System.Security.Cryptography.X509Certificates.X509Certificate2 CreateX509Cert2(string certName)
        {
            var keypairgen = new Org.BouncyCastle.Crypto.Generators.RsaKeyPairGenerator();

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

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

            // --- Until here we generate a keypair



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


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

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

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



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


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

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


            // -- Are these necessary ?

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


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

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


            gen.AddExtension(
                new Org.BouncyCastle.Asn1.DerObjectIdentifier("2.5.29.19"),
                false,
                new Org.BouncyCastle.Asn1.X509.BasicConstraints(false) // true if it is allowed to sign other certs
                );

            gen.AddExtension(
                new Org.BouncyCastle.Asn1.DerObjectIdentifier("2.5.29.15"),
                true,
                new Org.BouncyCastle.X509.X509KeyUsage(
                    Org.BouncyCastle.X509.X509KeyUsage.DigitalSignature |
                    Org.BouncyCastle.X509.X509KeyUsage.NonRepudiation |
                    Org.BouncyCastle.X509.X509KeyUsage.KeyEncipherment |
                    Org.BouncyCastle.X509.X509KeyUsage.DataEncipherment)
                );


            // -- End are these necessary ?

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

            bouncyCert.GetPublicKey();

            byte[] ba = bouncyCert.GetEncoded();

            using (System.IO.TextWriter textWriter = new System.IO.StringWriter())
            {
                Org.BouncyCastle.OpenSsl.PemWriter pemWriter = new Org.BouncyCastle.OpenSsl.PemWriter(textWriter);

                pemWriter.WriteObject(bouncyCert);
                pemWriter.WriteObject(keypair.Private);
                pemWriter.Writer.Flush();

                string privateKey = textWriter.ToString();
                System.Console.WriteLine(privateKey);
            } // End Using textWriter


            string certFile = @"D:\mycert.cert";

            using (System.IO.FileStream fs = System.IO.File.OpenWrite(certFile))
            {
                using (System.IO.TextWriter textWriter = new System.IO.StreamWriter(fs))
                {
                    Org.BouncyCastle.OpenSsl.PemWriter pemWriter = new Org.BouncyCastle.OpenSsl.PemWriter(textWriter);

                    pemWriter.WriteObject(bouncyCert);
                    pemWriter.WriteObject(keypair.Private);
                    pemWriter.Writer.Flush();

                    string privateKey = textWriter.ToString();
                    System.Console.WriteLine(privateKey);
                } // End Using textWriter
            }     // End Using fs


            // https://github.com/dotnet/corefx/blob/master/src/System.Security.Cryptography.X509Certificates/src/System/Security/Cryptography/X509Certificates/X509Certificate.cs
            // https://github.com/dotnet/corefx/blob/master/src/System.Security.Cryptography.X509Certificates/src/System/Security/Cryptography/X509Certificates/X509Certificate2.cs



            // System.Security.Cryptography.X509Certificates.X509Certificate2 msCert = new System.Security.Cryptography.X509Certificates.X509Certificate2(ba);
            System.Security.Cryptography.X509Certificates.X509Certificate2 msCert =
                new System.Security.Cryptography.X509Certificates
                .X509Certificate2(ba, null
                                  , System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable


                                  // System.Security.Cryptography.X509Certificates.X509KeyStorageFlag.PersistKeySet |
                                  // System.Security.Cryptography.X509Certificates.X509KeyStorageFlag.MachineKeySet |
                                  // System.Security.Cryptography.X509Certificates.X509KeyStorageFlag.Exportable
                                  );

            msCert = new X509Certificate2(certFile, null, X509KeyStorageFlags.MachineKeySet);
            object obj = msCert.GetRSAPrivateKey();

            System.Console.WriteLine(obj);

            if (msCert.HasPrivateKey)
            {
                Console.WriteLine(msCert.HasPrivateKey);
            }

            return(msCert);
        }