Generate() public method

Generate an X509Certificate.
public Generate ( AsymmetricKeyParameter privateKey ) : X509Certificate
privateKey Org.BouncyCastle.Crypto.AsymmetricKeyParameter The private key of the issuer that is signing this certificate.
return X509Certificate
        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;
            }
        }
Example #2
1
        public static X509Certificate2 GenerateSelfSigned(TimeSpan lifetime)
        {
            Guid guid = Guid.NewGuid();
            DateTime now = DateTime.UtcNow;
            SecureRandom rand = new SecureRandom();

            //Generate a key pair
            RsaKeyPairGenerator keyGen = new RsaKeyPairGenerator();
            keyGen.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(rand, 1024));
            AsymmetricCipherKeyPair key = keyGen.GenerateKeyPair();

            //Generate a certificate
            X509Name dn = new X509Name("CN=" + guid.ToString());
            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
            certGen.SetIssuerDN(dn);
            certGen.SetSerialNumber(new BigInteger(1, guid.ToByteArray()));
            certGen.SetSignatureAlgorithm("SHA1WITHRSA");
            certGen.SetSubjectDN(dn);
            certGen.SetPublicKey(key.Public);
            certGen.SetNotBefore(now);
            certGen.SetNotAfter(now.Add(lifetime));
            Org.BouncyCastle.X509.X509Certificate bcCert = certGen.Generate(key.Private);

            //Save it as pkcs12
            MemoryStream p12Stream = new MemoryStream();
            Pkcs12Store p12 = new Pkcs12Store();
            p12.SetKeyEntry("sts", new AsymmetricKeyEntry(key.Private), new X509CertificateEntry[] { new X509CertificateEntry(bcCert) });
            p12.Save(p12Stream, p12TmpPwd.ToCharArray(), rand);

            //Load the pkcs12 as .Net Certificate
            return new X509Certificate2(p12Stream.ToArray(), p12TmpPwd, X509KeyStorageFlags.DefaultKeySet);
        }
Example #3
0
        public static X509Certificate GenCert(CertInfo info)
        {
            RsaKeyPairGenerator _rsa = new RsaKeyPairGenerator();
            SecureRandom _random = new SecureRandom();

            _rsa.Init(new KeyGenerationParameters(_random, info.rsa_strength));
            AsymmetricCipherKeyPair _pair = _rsa.GenerateKeyPair();

            X509Name _cert_name = new X509Name("CN=" + info.name);
            BigInteger _serialnumber = BigInteger.ProbablePrime(120, new Random());

            X509V3CertificateGenerator _cert = new X509V3CertificateGenerator();
            _cert.SetSerialNumber(_serialnumber);
            _cert.SetSubjectDN(_cert_name);
            _cert.SetIssuerDN(_cert_name);
            _cert.SetNotBefore(info.begin_date);
            _cert.SetNotAfter(info.expire_date);
            _cert.SetSignatureAlgorithm("SHA1withRSA");
            _cert.SetPublicKey(_pair.Public);

            _cert.AddExtension(X509Extensions.ExtendedKeyUsage.Id, false,
                new AuthorityKeyIdentifier(
                    SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(_pair.Public),
                    new GeneralNames(new GeneralName(_cert_name)), _serialnumber));
            _cert.AddExtension(X509Extensions.ExtendedKeyUsage.Id, false,
                new ExtendedKeyUsage(new[] { KeyPurposeID.IdKPServerAuth }));

            return _cert.Generate(_pair.Private);
        }
Example #4
0
        public static Org.BouncyCastle.X509.X509Certificate CreateCert(String cn,
            AsymmetricKeyParameter pubKey, AsymmetricKeyParameter privKey)
        {
            Hashtable attrs = new Hashtable();
            attrs.Add(X509Name.CN, cn);

            ArrayList ord = new ArrayList(attrs.Keys);

            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);
            certGen.SetIssuerDN(new X509Name(ord, attrs));
            certGen.SetNotBefore(DateTime.UtcNow.AddDays(-30));
            certGen.SetNotAfter(DateTime.UtcNow.AddDays(30));
            certGen.SetSubjectDN(new X509Name(ord, attrs));
            certGen.SetPublicKey(pubKey);
            certGen.SetSignatureAlgorithm("SHA1WithRSAEncryption");

            Org.BouncyCastle.X509.X509Certificate cert = certGen.Generate(privKey);

            cert.CheckValidity(DateTime.UtcNow);

            cert.Verify(pubKey);

            return cert;
        }
Example #5
0
        /// <summary>
        /// Temporäres Zertifikat für Verschlüsselung und Signatur erstellen.
        /// </summary>
        /// <param name="name">Name</param>
        /// <param name="email">Email</param>
        /// <param name="producerId">Hersteller-ID</param>
        /// <param name="producerVersion">Hersteller-Version</param>
        /// <param name="locality">Ort</param>
        /// <param name="country">Land</param>
        /// <returns>Zertifikat</returns>
        public static SystemX509.X509Certificate2 CreateTemporaryCertificate(
            string name,
            string email,
            string producerId,
            string producerVersion,
            string locality,
            string country)
        {
            var rsaCrypto = new System.Security.Cryptography.RSACryptoServiceProvider(2048);
            var keyPair   = GetRsaKeyPair(rsaCrypto);

            var certGen = new Org.BouncyCastle.X509.X509V3CertificateGenerator();
            var now     = DateTime.Now;

            certGen.SetNotAfter(new DateTime(now.Year + 1, 12, 31, 23, 59, 59));

            var notBefore = new DateTime(now.Year, 1, 1);

            certGen.SetNotBefore(notBefore);
            certGen.SetSerialNumber(new Org.BouncyCastle.Math.BigInteger(string.Format("{0:yyyyMMdd}", notBefore)));

            var certName = new Org.BouncyCastle.Asn1.X509.X509Name(
                string.Format("CN={0}, O={1}, OU={2}, L={3}, C={4}", name, producerId, producerVersion, locality, country));

            certGen.SetSubjectDN(certName);
            certGen.SetIssuerDN(certName);
            certGen.SetPublicKey(keyPair.Public);

            var bcCert = certGen.Generate(new Asn1SignatureFactory("SHA256WITHRSA", keyPair.Private));
            var cert   = new SystemX509.X509Certificate2(bcCert.GetEncoded());

            cert = LinkPrivateKeyToCert(cert, rsaCrypto, null);

            return(cert);
        }
Example #6
0
        public static X509Certificate2 GenerateSelfSignedCert()
        {
            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);
            const string signatureAlgorithm = "SHA1WithRSA";
            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);
            var subjectDN = new X509Name("CN=simpletorrent");
            var issuerDN = subjectDN;
            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);
            var notBefore = DateTime.UtcNow.Date.AddHours(-24);
            var notAfter = notBefore.AddYears(1000);
            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);
            const int strength = 4096;
            var keyGenerationParameters = new KeyGenerationParameters(random, strength);

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

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

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

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

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

               string password = "******";

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

            //mono bug #1660 fix -> convert to definite-length encoding
            byte[] pfx = Pkcs12Utilities.ConvertToDefiniteLength(stream.ToArray(), password.ToCharArray());

            var convertedCertificate =
                new X509Certificate2(
                    pfx, password,
                    X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

            return convertedCertificate;
        }
            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;
        }
Example #8
0
		public static X509Certificate2 GenerateNewCertificate(string name)
		{
			var kpGen = new RsaKeyPairGenerator();
			kpGen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 1024));

			AsymmetricCipherKeyPair keyPair = kpGen.GenerateKeyPair();
			var gen = new X509V3CertificateGenerator();
			var certificateName = new X509Name("CN=" + name);
			BigInteger serialNumber = BigInteger.ProbablePrime(120, new Random());
			gen.SetSerialNumber(serialNumber);
			gen.SetSubjectDN(certificateName);
			gen.SetIssuerDN(certificateName);
			gen.SetNotAfter(DateTime.Now.AddYears(100));
			gen.SetNotBefore(DateTime.Now.AddDays(-1));
			gen.SetSignatureAlgorithm("SHA256WithRSAEncryption");
			gen.SetPublicKey(keyPair.Public);

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

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

			var newStore = new Pkcs12Store();

			var certEntry = new X509CertificateEntry(newCert);

			newStore.SetCertificateEntry(
				Environment.MachineName,
				certEntry
				);

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

			var memoryStream = new MemoryStream();
			newStore.Save(
				memoryStream,
				new char[0],
				new SecureRandom(new CryptoApiRandomGenerator())
				);

			return new X509Certificate2(memoryStream.ToArray());
		}
        public void TestX509CertificateConversion()
        {
            IBigInteger DSAParaG = new BigInteger(Base64.Decode("AL0fxOTq10OHFbCf8YldyGembqEu08EDVzxyLL29Zn/t4It661YNol1rnhPIs+cirw+yf9zeCe+KL1IbZ/qIMZM="));
            IBigInteger DSAParaP = new BigInteger(Base64.Decode("AM2b/UeQA+ovv3dL05wlDHEKJ+qhnJBsRT5OB9WuyRC830G79y0R8wuq8jyIYWCYcTn1TeqVPWqiTv6oAoiEeOs="));
            IBigInteger DSAParaQ = new BigInteger(Base64.Decode("AIlJT7mcKL6SUBMmvm24zX1EvjNx"));
            IBigInteger DSAPublicY = new BigInteger(Base64.Decode("TtWy2GuT9yGBWOHi1/EpCDa/bWJCk2+yAdr56rAcqP0eHGkMnA9s9GJD2nGU8sFjNHm55swpn6JQb8q0agrCfw=="));
            IBigInteger DsaPrivateX = new BigInteger(Base64.Decode("MMpBAxNlv7eYfxLTZ2BItJeD31A="));

            DsaParameters para = new DsaParameters(DSAParaP, DSAParaQ, DSAParaG);
            DsaPrivateKeyParameters dsaPriv = new DsaPrivateKeyParameters(DsaPrivateX, para);
            DsaPublicKeyParameters dsaPub = new DsaPublicKeyParameters(DSAPublicY, para);

            IDictionary attrs = new Hashtable();
            attrs[X509Name.C] = "AU";
            attrs[X509Name.O] = "The Legion of the Bouncy Castle";
            attrs[X509Name.L] = "Melbourne";
            attrs[X509Name.ST] = "Victoria";
            attrs[X509Name.E] = "*****@*****.**";

            IList ord = new ArrayList(attrs.Keys);

            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);

            certGen.SetIssuerDN(new X509Name(ord, attrs));
            certGen.SetNotBefore(DateTime.UtcNow.AddDays(-1));
            certGen.SetNotAfter(DateTime.UtcNow.AddDays(1));
            certGen.SetSubjectDN(new X509Name(ord, attrs));
            certGen.SetPublicKey(dsaPub);
            certGen.SetSignatureAlgorithm("SHA1WITHDSA");

            X509Certificate cert = certGen.Generate(dsaPriv);

            cert.CheckValidity();
            cert.Verify(dsaPub);

            SystemX509.X509Certificate dotNetCert = DotNetUtilities.ToX509Certificate(cert);

            X509Certificate certCopy = DotNetUtilities.FromX509Certificate(dotNetCert);

            Assert.AreEqual(cert, certCopy);

            certCopy.CheckValidity();
            certCopy.Verify(dsaPub);
        }
Example #10
0
		public static X509Certificate GenerateIntermediateCert(
			AsymmetricKeyParameter	intKey,
			AsymmetricKeyParameter	caKey,
			X509Certificate			caCert)
		{
			X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

			certGen.SetSerialNumber(BigInteger.One);
			certGen.SetIssuerDN(PrincipalUtilities.GetSubjectX509Principal(caCert));
			certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
			certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
			certGen.SetSubjectDN(new X509Name("CN=Test Intermediate Certificate"));
			certGen.SetPublicKey(intKey);
			certGen.SetSignatureAlgorithm("SHA256WithRSAEncryption");

			certGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert));
			certGen.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(intKey));
			certGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0));
			certGen.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyCertSign | KeyUsage.CrlSign));

			return certGen.Generate(caKey);
		}
        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();
            }
        }
Example #12
0
	// Send either ValidatePair or Pair (depending on Action)
	// request to iPhone and return true upon success or false otherwise.
	private bool Pair(PairAction Action)
	{
		#region Preparation of certificates
		X509V3CertificateGenerator DeviceCG = new X509V3CertificateGenerator();
		DeviceCG.SetPublicKey(DevicePublicKey);
		DeviceCG.SetSerialNumber(Org.BouncyCastle.Math.BigInteger.Zero);
		DeviceCG.SetNotBefore(iPhone.RootCertificate.NotBefore);
		DeviceCG.SetNotAfter(iPhone.RootCertificate.NotAfter);
		DeviceCG.SetSignatureAlgorithm("SHA1WithRSAEncryption");
		DeviceCG.AddExtension(Org.BouncyCastle.Asn1.X509.X509Extensions.BasicConstraints, true, new Org.BouncyCastle.Asn1.X509.BasicConstraints(false));
		DeviceCertificate = DeviceCG.Generate(iPhone.RootKey.Private);

		// The \n at the end of these certificates is crucial; hung me up for a while.
		string sDeviceCertificate = "-----BEGIN CERTIFICATE-----\n"
									+ Convert.ToBase64String(DeviceCertificate.GetEncoded())
									+ "\n-----END CERTIFICATE-----\n";
		byte[] bDeviceCertificate = System.Text.Encoding.UTF8.GetBytes(sDeviceCertificate);
		string sHostCertificate = "-----BEGIN CERTIFICATE-----\n"
									+ Convert.ToBase64String(iPhone.HostCertificate.GetEncoded())
									+ "\n-----END CERTIFICATE-----\n";
		byte[] bHostCertificate = System.Text.Encoding.UTF8.GetBytes(sHostCertificate);
		string sRootCertificate = "-----BEGIN CERTIFICATE-----\n"
									+ Convert.ToBase64String(iPhone.RootCertificate.GetEncoded())
									+ "\n-----END CERTIFICATE-----\n";
		byte[] bRootCertificate = System.Text.Encoding.UTF8.GetBytes(sRootCertificate);
		#endregion

		MemoryStream MS = new MemoryStream();
		XmlWriter XTW = XmlWriter.Create(MS, XWS);
		XTW.WriteStartDocument();
		XTW.WriteDocType("plist", sApplePubID, sAppleSysID, null);
		XTW.WriteStartElement("plist");
		XTW.WriteAttributeString("version", "1.0");
		XTW.WriteStartElement("dict");

		XTW.WriteElementString("key", "PairRecord");
		XTW.WriteStartElement("dict");

		XTW.WriteElementString("key", "DeviceCertificate");
		XTW.WriteStartElement("data");
		XTW.WriteBase64(bDeviceCertificate, 0, bDeviceCertificate.Length);
		XTW.WriteEndElement(); // DeviceCertificate data

		XTW.WriteElementString("key", "HostCertificate");
		XTW.WriteStartElement("data");
		XTW.WriteBase64(bHostCertificate, 0, bHostCertificate.Length);
		XTW.WriteEndElement(); // HostCertificate data

		XTW.WriteElementString("key", "HostID");
		XTW.WriteElementString("string", iPhone.sHostID);
		XTW.WriteElementString("key", "RootCertificate");
		XTW.WriteStartElement("data");
		XTW.WriteBase64(bRootCertificate, 0, bRootCertificate.Length);
		XTW.WriteEndElement(); // RootCertificate data

		XTW.WriteEndElement(); // inner dict

		XTW.WriteElementString("key", "Request");
		switch (Action)
		{
			case PairAction.Pair:
				XTW.WriteElementString("string", "Pair");
				break;

			case PairAction.ValidatePair:
				XTW.WriteElementString("string", "ValidatePair");
				break;

			case PairAction.Unpair:
				XTW.WriteElementString("string", "Unpair");
				break;
		}

		XTW.WriteEndElement(); // outer dict
		XTW.WriteEndElement(); // plist
		XTW.WriteEndDocument();
		XTW.Flush();

		byte[] bXMLData = MS.GetBuffer();
		XTW.Close(); // Closes MS, too.

		PListSend(bXMLData);
		bXMLData = PListReceive();

		if (!CheckXMLForSuccess(bXMLData))
			return false;

		// Have to validate after pairing for "trusted host status", apparently.
		if (Action == PairAction.Pair)
			return Pair(PairAction.ValidatePair);

		return true;
	}
        public static byte[] GenerateDsaCertificateAsPkcs12(
            string friendlyName,
            string subjectName,
            string country,
            DateTime validStartDate,
            DateTime validEndDate,
            string password,
            Org.BouncyCastle.X509.X509Certificate caCert,
            AsymmetricKeyParameter caPrivateKey)
        {
            var keys = GenerateDsaKeys();

            #region build certificate
            var certGen = new X509V3CertificateGenerator();

            // build name attributes
            var nameOids = new ArrayList();
            nameOids.Add(Org.BouncyCastle.Asn1.X509.X509Name.CN);
            nameOids.Add(X509Name.O);
            nameOids.Add(X509Name.C);

            var nameValues = new ArrayList();
            nameValues.Add(friendlyName);
            nameValues.Add(subjectName);
            nameValues.Add(country);
            var subjectDN = new X509Name(nameOids, nameValues);

            // certificate fields
            certGen.SetSerialNumber(BigInteger.ValueOf(1));
            certGen.SetIssuerDN(caCert.SubjectDN);
            certGen.SetNotBefore(validStartDate);
            certGen.SetNotAfter(validEndDate);
            certGen.SetSubjectDN(subjectDN);
            certGen.SetPublicKey(keys.Public);
            certGen.SetSignatureAlgorithm("SHA1withDSA");

            // extended information
            certGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert.GetPublicKey()));
            certGen.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keys.Public));
            #endregion

            // generate x509 certificate
            var cert = certGen.Generate(caPrivateKey);
            //ert.Verify(caCert.GetPublicKey());

            var chain = new Dictionary<string, Org.BouncyCastle.X509.X509Certificate>();
            //chain.Add("CertiFirmas CA", caCert);
            var caCn = caCert.SubjectDN.GetValues(X509Name.CN)[0].ToString();
            chain.Add(caCn, caCert);

            // store the file
            return GeneratePkcs12(keys, cert, friendlyName, password, chain);
        }
Example #14
0
        private void doTestNullDerNullCert()
        {
            AsymmetricCipherKeyPair keyPair = GenerateLongFixedKeys();

            AsymmetricKeyParameter pubKey = keyPair.Public;
            AsymmetricKeyParameter privKey = keyPair.Private;

            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);
            certGen.SetIssuerDN(new X509Name("CN=Test"));
            certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
            certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
            certGen.SetSubjectDN(new X509Name("CN=Test"));
            certGen.SetPublicKey(pubKey);
            certGen.SetSignatureAlgorithm("MD5WithRSAEncryption");
            X509Certificate cert = certGen.Generate(privKey);

            X509CertificateStructure certStruct = X509CertificateStructure.GetInstance(
                Asn1Object.FromByteArray(cert.GetEncoded()));

            Asn1Encodable tbsCertificate = certStruct.TbsCertificate;
            AlgorithmIdentifier sig = certStruct.SignatureAlgorithm;

            DerSequence seq = new DerSequence(
                tbsCertificate,
                new AlgorithmIdentifier(sig.Algorithm),
                certStruct.Signature);

            try
            {
                // verify
                byte[] encoded = seq.GetEncoded();
                X509CertificateParser fact = new X509CertificateParser();
                cert = fact.ReadCertificate(encoded);
                cert.Verify(cert.GetPublicKey());
            }
            catch (Exception e)
            {
                Fail("doTestNullDerNull failed - exception " + e.ToString(), e);
            }
        }
Example #15
0
        internal void checkCreation5()
        {
            //
            // a sample key pair.
            //
            RsaKeyParameters pubKey = new RsaKeyParameters(
                false,
                new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16),
                new BigInteger("11", 16));

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

            //
            // set up the keys
            //
            SecureRandom rand = new SecureRandom();
//			AsymmetricKeyParameter privKey;
//			AsymmetricKeyParameter pubKey;
//
//			KeyFactory  fact = KeyFactory.GetInstance("RSA");
//
//			privKey = fact.generatePrivate(privKeySpec);
//			pubKey = fact.generatePublic(pubKeySpec);

            //
            // distinguished name table.
            //
            IList ord = new ArrayList();
            ord.Add(X509Name.C);
            ord.Add(X509Name.O);
            ord.Add(X509Name.L);
            ord.Add(X509Name.ST);
            ord.Add(X509Name.E);

            IList values = new ArrayList();
            values.Add("AU");
            values.Add("The Legion of the Bouncy Castle");
            values.Add("Melbourne");
            values.Add("Victoria");
            values.Add("*****@*****.**");

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

            certGen.SetSerialNumber(BigInteger.One);
            certGen.SetIssuerDN(new X509Name(ord, values));
            certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
            certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
            certGen.SetSubjectDN(new X509Name(ord, values));
            certGen.SetPublicKey(pubKey);
            certGen.SetSignatureAlgorithm("MD5WithRSAEncryption");
            certGen.AddExtension("2.5.29.15", true,
                new X509KeyUsage(X509KeyUsage.EncipherOnly));
            certGen.AddExtension("2.5.29.37", true,
                new DerSequence(KeyPurposeID.AnyExtendedKeyUsage));
            certGen.AddExtension("2.5.29.17", true,
                new GeneralNames(new GeneralName(GeneralName.Rfc822Name, "*****@*****.**")));

            X509Certificate baseCert = certGen.Generate(privKey);

            //
            // copy certificate
            //
            certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);
            certGen.SetIssuerDN(new X509Name(ord, values));
            certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
            certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
            certGen.SetSubjectDN(new X509Name(ord, values));
            certGen.SetPublicKey(pubKey);
            certGen.SetSignatureAlgorithm("MD5WithRSAEncryption");

            certGen.CopyAndAddExtension(new DerObjectIdentifier("2.5.29.15"), true, baseCert);
            certGen.CopyAndAddExtension("2.5.29.37", false, baseCert);

            X509Certificate cert = certGen.Generate(privKey);

            cert.CheckValidity(DateTime.UtcNow);

            cert.Verify(pubKey);

            DerObjectIdentifier oid1 = new DerObjectIdentifier("2.5.29.15");
            if (!baseCert.GetExtensionValue(oid1).Equals(cert.GetExtensionValue(oid1)))
            {
                Fail("2.5.29.15 differs");
            }

            DerObjectIdentifier oid2 = new DerObjectIdentifier("2.5.29.37");
            if (!baseCert.GetExtensionValue(oid2).Equals(cert.GetExtensionValue(oid2)))
            {
                Fail("2.5.29.37 differs");
            }

            //
            // exception test
            //
            try
            {
                certGen.CopyAndAddExtension("2.5.99.99", true, baseCert);

                Fail("exception not thrown on dud extension copy");
            }
            catch (CertificateParsingException)
            {
                // expected
            }

            try
            {
                certGen.SetPublicKey(dudPublicKey);

                certGen.Generate(privKey);

                Fail("key without encoding not detected in v3");
            }
            catch (ArgumentException)
            {
                // expected
            }
        }
Example #16
0
        /**
         * we Generate a self signed certificate for the sake of testing - SHA224withECDSA
         */
        private void createECCert(
            string				algorithm,
            DerObjectIdentifier	algOid)
        {
            FpCurve curve = new FpCurve(
                new BigInteger("6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151"), // q (or p)
                new BigInteger("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC", 16),   // a
                new BigInteger("0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00", 16));  // b

            ECDomainParameters spec = new ECDomainParameters(
                curve,
//				curve.DecodePoint(Hex.Decode("02C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66")), // G
                curve.DecodePoint(Hex.Decode("0200C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66")), // G
                new BigInteger("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409", 16)); // n

            ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(
                "ECDSA",
                new BigInteger("5769183828869504557786041598510887460263120754767955773309066354712783118202294874205844512909370791582896372147797293913785865682804434049019366394746072023"), // d
                spec);

            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
                "ECDSA",
//				curve.DecodePoint(Hex.Decode("026BFDD2C9278B63C92D6624F151C9D7A822CC75BD983B17D25D74C26740380022D3D8FAF304781E416175EADF4ED6E2B47142D2454A7AC7801DD803CF44A4D1F0AC")), // Q
                curve.DecodePoint(Hex.Decode("02006BFDD2C9278B63C92D6624F151C9D7A822CC75BD983B17D25D74C26740380022D3D8FAF304781E416175EADF4ED6E2B47142D2454A7AC7801DD803CF44A4D1F0AC")), // Q
                spec);

//			//
//			// set up the keys
//			//
//			AsymmetricKeyParameter privKey;
//			AsymmetricKeyParameter pubKey;
//
//			KeyFactory fact = KeyFactory.GetInstance("ECDSA");
//
//			privKey = fact.generatePrivate(privKeySpec);
//			pubKey = fact.generatePublic(pubKeySpec);


            //
            // distinguished name table.
            //
            IDictionary attrs = new Hashtable();
            IList order = new ArrayList();

            attrs.Add(X509Name.C, "AU");
            attrs.Add(X509Name.O, "The Legion of the Bouncy Castle");
            attrs.Add(X509Name.L, "Melbourne");
            attrs.Add(X509Name.ST, "Victoria");
            attrs.Add(X509Name.E, "*****@*****.**");

            order.Add(X509Name.C);
            order.Add(X509Name.O);
            order.Add(X509Name.L);
            order.Add(X509Name.ST);
            order.Add(X509Name.E);

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

            certGen.SetSerialNumber(BigInteger.One);
            certGen.SetIssuerDN(new X509Name(order, attrs));
            certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
            certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
            certGen.SetSubjectDN(new X509Name(order, attrs));
            certGen.SetPublicKey(pubKey);
            certGen.SetSignatureAlgorithm(algorithm);


            X509Certificate cert = certGen.Generate(privKey);

            cert.CheckValidity(DateTime.UtcNow);

            cert.Verify(pubKey);

            X509CertificateParser fact = new X509CertificateParser();
            cert = fact.ReadCertificate(cert.GetEncoded());

            //
            // try with point compression turned off
            //
//			((ECPointEncoder)pubKey).setPointFormat("UNCOMPRESSED");
            ECPoint q = pubKey.Q.Normalize();
            pubKey = new ECPublicKeyParameters(
                pubKey.AlgorithmName,
                q.Curve.CreatePoint(q.XCoord.ToBigInteger(), q.YCoord.ToBigInteger()),
                pubKey.Parameters);

            certGen.SetPublicKey(pubKey);

            cert = certGen.Generate(privKey);

            cert.CheckValidity(DateTime.UtcNow);

            cert.Verify(pubKey);

            cert = fact.ReadCertificate(cert.GetEncoded());

            if (!cert.SigAlgOid.Equals(algOid.ToString()))
            {
                Fail("ECDSA oid incorrect.");
            }

            if (cert.GetSigAlgParams() != null)
            {
                Fail("sig parameters present");
            }

            ISigner sig = SignerUtilities.GetSigner(algorithm);

            sig.Init(false, pubKey);

            byte[] b = cert.GetTbsCertificate();
            sig.BlockUpdate(b, 0, b.Length);

            if (!sig.VerifySignature(cert.GetSignature()))
            {
                Fail("EC certificate signature not mapped correctly.");
            }
            // Console.WriteLine(cert);
        }
Example #17
0
        /**
         * we Generate a self signed certificate for the sake of testing - DSA
         */
        internal void checkCreation2()
        {
            //
            // set up the keys
            //
            AsymmetricKeyParameter privKey;
            AsymmetricKeyParameter pubKey;

            try
            {
//				KeyPairGenerator g = KeyPairGenerator.GetInstance("DSA", "SUN");
//				g.initialize(512, new SecureRandom());
//				KeyPair p = g.generateKeyPair();
                IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("DSA");
                DsaParametersGenerator dpg = new DsaParametersGenerator();
                dpg.Init(512, 25, new SecureRandom());
                g.Init(new DsaKeyGenerationParameters(new SecureRandom(), dpg.GenerateParameters()));
                AsymmetricCipherKeyPair p = g.GenerateKeyPair();

                privKey = p.Private;
                pubKey = p.Public;
            }
            catch (Exception e)
            {
                Fail("error setting up keys - " + e.ToString());
                return;
            }

            //
            // distinguished name table.
            //
            IList ord = new ArrayList();
            ord.Add(X509Name.C);
            ord.Add(X509Name.O);
            ord.Add(X509Name.L);
            ord.Add(X509Name.ST);
            ord.Add(X509Name.E);

            IList values = new ArrayList();
            values.Add("AU");
            values.Add("The Legion of the Bouncy Castle");
            values.Add("Melbourne");
            values.Add("Victoria");
            values.Add("*****@*****.**");

            //
            // extensions
            //

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

            certGen.SetSerialNumber(BigInteger.One);
            certGen.SetIssuerDN(new X509Name(ord, values));
            certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
            certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
            certGen.SetSubjectDN(new X509Name(ord, values));
            certGen.SetPublicKey(pubKey);
            certGen.SetSignatureAlgorithm("SHA1withDSA");

            try
            {
                X509Certificate cert = certGen.Generate(privKey);

                cert.CheckValidity(DateTime.UtcNow);

                cert.Verify(pubKey);

                cert = new X509CertificateParser().ReadCertificate(cert.GetEncoded());

                // Console.WriteLine(cert);
            }
            catch (Exception e)
            {
                Fail("error setting generating cert - " + e.ToString());
            }

            //
            // create the certificate - version 1
            //
            X509V1CertificateGenerator certGen1 = new X509V1CertificateGenerator();

            certGen1.SetSerialNumber(BigInteger.One);
            certGen1.SetIssuerDN(new X509Name(ord, values));
            certGen1.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
            certGen1.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
            certGen1.SetSubjectDN(new X509Name(ord, values));
            certGen1.SetPublicKey(pubKey);
            certGen1.SetSignatureAlgorithm("SHA1withDSA");

            try
            {
                X509Certificate cert = certGen1.Generate(privKey);

                cert.CheckValidity(DateTime.UtcNow);

                cert.Verify(pubKey);

                cert = new X509CertificateParser().ReadCertificate(cert.GetEncoded());

                //Console.WriteLine(cert);
            }
            catch (Exception e)
            {
                Fail("error setting generating cert - " + e.ToString());
            }

            //
            // exception test
            //
            try
            {
                certGen.SetPublicKey(dudPublicKey);

                Fail("key without encoding not detected in v1");
            }
            catch (ArgumentException)
            {
                // expected
            }
        }
Example #18
0
		/**
		* we generate a self signed certificate for the sake of testing - RSA
		*/
		public X509CertificateEntry CreateCert(
			AsymmetricKeyParameter	pubKey,
			AsymmetricKeyParameter	privKey,
			string					issuerEmail,
			string					subjectEmail)
		{
			//
			// distinguished name table.
			//
            IDictionary issuerAttrs = new Hashtable();
			issuerAttrs.Add(X509Name.C, "AU");
			issuerAttrs.Add(X509Name.O, "The Legion of the Bouncy Castle");
			issuerAttrs.Add(X509Name.L, "Melbourne");
			issuerAttrs.Add(X509Name.ST, "Victoria");
			issuerAttrs.Add(X509Name.EmailAddress, issuerEmail);

			IDictionary subjectAttrs = new Hashtable();
			subjectAttrs.Add(X509Name.C, "AU");
			subjectAttrs.Add(X509Name.O, "The Legion of the Bouncy Castle");
			subjectAttrs.Add(X509Name.L, "Melbourne");
			subjectAttrs.Add(X509Name.ST, "Victoria");
			subjectAttrs.Add(X509Name.EmailAddress, subjectEmail);

			IList order = new ArrayList();
			order.Add(X509Name.C);
			order.Add(X509Name.O);
			order.Add(X509Name.L);
			order.Add(X509Name.ST);
			order.Add(X509Name.EmailAddress);

			//
			// extensions
			//

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

			certGen.SetSerialNumber(BigInteger.One);
			certGen.SetIssuerDN(new X509Name(order, issuerAttrs));
			certGen.SetNotBefore(DateTime.UtcNow.AddDays(-30));
			certGen.SetNotAfter(DateTime.UtcNow.AddDays(30));
			certGen.SetSubjectDN(new X509Name(order, subjectAttrs));
			certGen.SetPublicKey(pubKey);
			certGen.SetSignatureAlgorithm("MD5WithRSAEncryption");

			return new X509CertificateEntry(certGen.Generate(privKey));
		}
Example #19
0
	private bool Initialize()
	{
		if (!Usable) return false;

		ErrorCode EC = ErrorCode.None;
		int nBytesWritten, nBytesRead;

		try
		{
			// Flush the device by reading until there's nothing left to read.
			byte[] byBuffer = new byte[1024];
			while (true)
			{
				iPhoneEndpointReader.Read(byBuffer, 10, out nBytesRead);
				if (nBytesRead == 0 || EC != ErrorCode.None) break;
			}

			Global.Log("Saying hi to device... ");
			EC = iPhoneEndpointWriter.Write(iPhoneVersionHeader(), nDefaultTimeout, out nBytesWritten);
			if (EC != ErrorCode.None) throw new Exception(UsbDevice.LastErrorString);
			if (nBytesWritten != 20) throw new Exception("<20 bytes written. 20 expected.");

			EC = iPhoneEndpointReader.Read(byBuffer, nDefaultTimeout, out nBytesRead);
			if (EC != ErrorCode.None)
			{
				Global.Log("failed! Is the device currently locked by a passcode? If not, replug it.\n", true);
				throw new Exception(UsbDevice.LastErrorString);
			}

			if (nBytesRead != 20)
			{
				Global.Log("failed!\n", true);
				throw new Exception("Device won't talk. Re-plug it.");
			}

			Global.Log("success!\n", true);

			int nTemp = 0;
			MemoryStream MS = new MemoryStream(byBuffer);
			BinaryReader BR = new BinaryReader(MS);
			MS.Seek(8, SeekOrigin.Begin);
			nTemp = System.Net.IPAddress.NetworkToHostOrder(BR.ReadInt32());
			if (nTemp != 1) throw new Exception("iPhone major version != 1");
			nTemp = System.Net.IPAddress.NetworkToHostOrder(BR.ReadInt32());
			if (nTemp != 0) throw new Exception("iPhone minor version != 1");
			BR.Close();
			MS.Close();
		}
		catch (Exception ex)
		{
			Global.Log((EC != ErrorCode.None ? EC + ":" : String.Empty) + ex.Message + "\n");
			return false;
		}

		Global.Log("Starting up lockdownd... ");
		try { Lockdown = new LockdownConnection(this); }
		catch (Exception e)
		{
			Global.Log("failed!\n", true);
			throw e;
		}
		MUXConnections.Add(Lockdown);
		Global.Log("success!\n", true);

		_DeviceName = Lockdown.GetDeviceName();
		_UniqueDeviceID = Lockdown.GetUniqueDeviceID();

		#region Preparation of cryptography stuff
		if (LoadCryptoStuffFromRegistry() == false)
		{
			Global.Log("Haven't seen this device before. Creating new RSA keys.\n");

			// First generate "root" and "host" private keys and X.509 certificates.
			X509V3CertificateGenerator RootCG = new X509V3CertificateGenerator();
			Org.BouncyCastle.Crypto.Generators.RsaKeyPairGenerator RootRKPG = new Org.BouncyCastle.Crypto.Generators.RsaKeyPairGenerator();
			RootRKPG.Init(new KeyGenerationParameters(new Org.BouncyCastle.Security.SecureRandom(), 1024));
			Global.Log("Generating RSA key pair for root... ");
			RootKey = RootRKPG.GenerateKeyPair();
			Global.Log("success!\n", true);

			// Outdated certificate preparation, was not compatible with iOS4
			/*System.Security.Cryptography.X509Certificates.X509Certificate C = new System.Security.Cryptography.X509Certificates.X509Certificate();
			RootCG.SetPublicKey(RootKey.Public);
			RootCG.SetSerialNumber(Org.BouncyCastle.Math.BigInteger.One);
			RootCG.SetNotBefore(StartTime);
			RootCG.SetNotAfter(new DateTime(StartTime.Ticks + ((long)10000000 * 60 * 60 * 24 * 365 * 10)));
			// Issuer and subject stuff are irrelevant but BouncyCastle won't accept null inputs.
			RootCG.SetIssuerDN(new Org.BouncyCastle.Asn1.X509.X509Name(new ArrayList(), new ArrayList()));
			RootCG.SetSubjectDN(new Org.BouncyCastle.Asn1.X509.X509Name(new ArrayList(), new ArrayList()));
			RootCG.SetSignatureAlgorithm("SHA1WithRSAEncryption");
			RootCG.AddExtension(Org.BouncyCastle.Asn1.X509.X509Extensions.BasicConstraints, true, new Org.BouncyCastle.Asn1.X509.BasicConstraints(true));
			//Org.BouncyCastle.Asn1.X509.SubjectKeyIdentifier RootSKI = new Org.BouncyCastle.X509.Extension.SubjectKeyIdentifierStructure(RootKey.Public);
			//RootCG.AddExtension(Org.BouncyCastle.Asn1.X509.X509Extensions.SubjectKeyIdentifier, false, RootSKI);
			RootCertificate = RootCG.Generate(RootKey.Private);*/

			System.Security.Cryptography.X509Certificates.X509Certificate C = new System.Security.Cryptography.X509Certificates.X509Certificate();
			RootCG.SetPublicKey(RootKey.Public);
			RootCG.SetSerialNumber(Org.BouncyCastle.Math.BigInteger.Zero);
			RootCG.SetNotBefore(StartTime);
			RootCG.SetNotAfter(new DateTime(StartTime.Ticks + ((long)10000000 * 60 * 60 * 24 * 365 * 10)));
			RootCG.SetSignatureAlgorithm("SHA1WithRSAEncryption");
			RootCG.AddExtension(Org.BouncyCastle.Asn1.X509.X509Extensions.BasicConstraints, true, new Org.BouncyCastle.Asn1.X509.BasicConstraints(true));
			RootCertificate = RootCG.Generate(RootKey.Private);

			X509V3CertificateGenerator HostCG = new X509V3CertificateGenerator();
			Org.BouncyCastle.Crypto.Generators.RsaKeyPairGenerator HostRKPG = new Org.BouncyCastle.Crypto.Generators.RsaKeyPairGenerator();
			HostRKPG.Init(new KeyGenerationParameters(new Org.BouncyCastle.Security.SecureRandom(), 1024));
			Global.Log("Generating RSA key pair for host... ");
			HostKey = HostRKPG.GenerateKeyPair();
			Global.Log("success!\n", true);

			HostCG.SetPublicKey(HostKey.Public);
			HostCG.SetSerialNumber(Org.BouncyCastle.Math.BigInteger.Zero);
			HostCG.SetNotBefore(RootCertificate.NotBefore);
			HostCG.SetNotAfter(RootCertificate.NotAfter);
			HostCG.SetSignatureAlgorithm("SHA1WithRSAEncryption");
			HostCG.AddExtension(Org.BouncyCastle.Asn1.X509.X509Extensions.BasicConstraints, true, new Org.BouncyCastle.Asn1.X509.BasicConstraints(false));
			HostCG.AddExtension(Org.BouncyCastle.Asn1.X509.X509Extensions.KeyUsage, true,
					new Org.BouncyCastle.Asn1.X509.KeyUsage(Org.BouncyCastle.Asn1.X509.KeyUsage.KeyEncipherment | Org.BouncyCastle.Asn1.X509.KeyUsage.DigitalSignature));
			HostCertificate = HostCG.Generate(RootKey.Private);
		}
		else
			Global.Log("Loaded RSA stuff from registry.\n");
		#endregion

		try { Lockdown.Authenticate(); }
		catch (Exception e)
		{
			Global.Log("Exception encountered during authentication:\n" + e);
			Shutdown(false);
			return false;
		}

		return true;
	}
        /// <summary>
        /// Generate a certificate signed by a CA certificate
        /// </summary>
        /// <param name="caKeyPair">Asymmetric key pair used to generate CA certificate</param>
        /// <param name="caCertificate">CA certificate</param>
        /// <param name="keyPair">Asymmetric key pair to use for generating certificate</param>
        /// <param name="certificateDetails">Certificate details </param>
        /// <param name="certificateDetailsOrder">Order certificate details are created</param>
        /// <returns></returns>
        public X509Certificate GenerateCertificateSignedWithCaCertificate(AsymmetricCipherKeyPair caKeyPair, X509Certificate caCertificate, AsymmetricCipherKeyPair keyPair, IDictionary certificateDetails, IList certificateDetailsOrder)
        {
            var startDate = DateTime.UtcNow.AddYears(-1);              // time from which certificate is valid
            var expiryDate = startDate.AddYears(20);      // time after which certificate is not valid
            var serialNumber = BigInteger.ProbablePrime(120, new Random());
            var certName = new X509Name(certificateDetailsOrder, certificateDetails);

            var x509V3CertificateGenerator = new X509V3CertificateGenerator();
            x509V3CertificateGenerator.SetSerialNumber(serialNumber);
            x509V3CertificateGenerator.SetSubjectDN(certName);
            x509V3CertificateGenerator.SetIssuerDN(caCertificate.SubjectDN);
            x509V3CertificateGenerator.SetNotBefore(startDate);
            x509V3CertificateGenerator.SetNotAfter(expiryDate);
            x509V3CertificateGenerator.SetSignatureAlgorithm(SignatureAlgorithm);
            x509V3CertificateGenerator.SetPublicKey(keyPair.Public);

            //Public key to use
            x509V3CertificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.Public));

            //CA Certificate used to sign certificate
            x509V3CertificateGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCertificate));

            //Sign it with CA private key
            var newCert = x509V3CertificateGenerator.Generate(caKeyPair.Private);

            return newCert;
        }
        /*
         * creates a certificate and a private key and installs into windows registry
         */
        public static void CreateCertificateKey(
            string subjectName,
            string issuerName,
            string signatureAlgorithm,
            int strength,
            DateTime begin,
            DateTime end,
            string subjectCountryCode,
            string subjectOrganization,
            string subjectTitle,
            string issuerCountryCode,
            string issuerOrganization,
            string issuerTitle,
            string subjectCommonName,
            string issuerCommonName)
        {
            RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator();
            SecureRandom secureRandom = new SecureRandom(new CryptoApiRandomGenerator());
            keyPairGenerator.Init(new KeyGenerationParameters(secureRandom, strength));
            AsymmetricCipherKeyPair asCipherKeyPair = keyPairGenerator.GenerateKeyPair();
            AsymmetricKeyParameter publicKey = asCipherKeyPair.Public;
            RsaPrivateCrtKeyParameters privateKey = (RsaPrivateCrtKeyParameters)asCipherKeyPair.Private;

            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
            BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), secureRandom);
            certificateGenerator.SetSerialNumber(serialNumber);

            string subjectNameString = "E=" + subjectName;
            if (subjectCommonName != null)
                subjectNameString += ", CN=" + subjectCommonName;
            if (subjectCountryCode != null)
                subjectNameString += ", C=" + subjectCountryCode;
            if (subjectOrganization != null)
                subjectNameString += ", O=" + subjectOrganization;
            if (subjectTitle != null)
                subjectNameString += ", T=" + subjectTitle;
            certificateGenerator.SetSubjectDN(new X509Name(subjectNameString));

            string issuerNameString = "E=" + issuerName;
            if (issuerCommonName != null)
                issuerNameString += ", CN=" + issuerCommonName;
            if (issuerCountryCode != null)
                issuerNameString += ", C=" + issuerCountryCode;
            if (issuerOrganization != null)
                issuerNameString += ", O=" + issuerOrganization;
            if (issuerTitle != null)
                issuerNameString += ", T=" + issuerTitle;
            certificateGenerator.SetIssuerDN(new X509Name(issuerNameString));

            certificateGenerator.SetNotBefore(begin);
            certificateGenerator.SetNotAfter(end);
            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);
            certificateGenerator.SetPublicKey(publicKey);

            X509Certificate certificate = certificateGenerator.Generate(privateKey);
            sys.X509Certificate2 windowsCertificate = new sys.X509Certificate2(DotNetUtilities.ToX509Certificate(certificate));
            windowsCertificate.PrivateKey = ConvertToSystemKey(privateKey);

            InstallIntoRegistry(windowsCertificate);
        }
Example #22
0
		public static X509Certificate MakeCertificate(AsymmetricCipherKeyPair _subKP,
			string _subDN, AsymmetricCipherKeyPair _issKP, string _issDN, 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("MD5WithRSAEncryption");

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

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

			if (_ca)
			{
				_v3CertGen.AddExtension(X509Extensions.BasicConstraints, false,
						new BasicConstraints(_ca));
			}
			else
			{
				_v3CertGen.AddExtension(X509Extensions.ExtendedKeyUsage, true,
					ExtendedKeyUsage.GetInstance(new DerSequence(KeyPurposeID.IdKPTimeStamping)));
			}

			X509Certificate _cert = _v3CertGen.Generate(_issPriv);

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

			return _cert;
		}
Example #23
0
        /**
         * we Generate a self signed certificate for the sake of testing - RSA
         */
        internal void checkCreation1()
        {
            //
            // a sample key pair.
            //
            RsaKeyParameters pubKey = new RsaKeyParameters(
                false,
                new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16),
                new BigInteger("11", 16));

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

            //
            // set up the keys
            //
//			AsymmetricKeyParameter privKey;
//			AsymmetricKeyParameter pubKey;

//			KeyFactory  fact = KeyFactory.GetInstance("RSA");
//
//			privKey = fact.generatePrivate(privKeySpec);
//			pubKey = fact.generatePublic(pubKeySpec);

            //
            // distinguished name table.
            //
            IList ord = new ArrayList();
            ord.Add(X509Name.C);
            ord.Add(X509Name.O);
            ord.Add(X509Name.L);
            ord.Add(X509Name.ST);
            ord.Add(X509Name.E);

            IList values = new ArrayList();
            values.Add("AU");
            values.Add("The Legion of the Bouncy Castle");
            values.Add("Melbourne");
            values.Add("Victoria");
            values.Add("*****@*****.**");

            //
            // extensions
            //

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

            certGen.SetSerialNumber(BigInteger.One);
            certGen.SetIssuerDN(new X509Name(ord, values));
            certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
            certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
            certGen.SetSubjectDN(new X509Name(ord, values));
            certGen.SetPublicKey(pubKey);
            certGen.SetSignatureAlgorithm("SHA256WithRSAEncryption");

            X509Certificate cert = certGen.Generate(privKey);

            cert.CheckValidity(DateTime.UtcNow);

            cert.Verify(pubKey);

            ISet dummySet = cert.GetNonCriticalExtensionOids();
            if (dummySet != null)
            {
                Fail("non-critical oid set should be null");
            }
            dummySet = cert.GetCriticalExtensionOids();
            if (dummySet != null)
            {
                Fail("critical oid set should be null");
            }

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

            certGen.SetSerialNumber(BigInteger.One);
            certGen.SetIssuerDN(new X509Name(ord, values));
            certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
            certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
            certGen.SetSubjectDN(new X509Name(ord, values));
            certGen.SetPublicKey(pubKey);
            certGen.SetSignatureAlgorithm("MD5WithRSAEncryption");
            certGen.AddExtension("2.5.29.15", true,
                new X509KeyUsage(X509KeyUsage.EncipherOnly));
            certGen.AddExtension("2.5.29.37", true,
                new DerSequence(KeyPurposeID.AnyExtendedKeyUsage));
            certGen.AddExtension("2.5.29.17", true,
                new GeneralNames(new GeneralName(GeneralName.Rfc822Name, "*****@*****.**")));

            cert = certGen.Generate(privKey);

            cert.CheckValidity(DateTime.UtcNow);

            cert.Verify(pubKey);

            cert = new X509CertificateParser().ReadCertificate(cert.GetEncoded());

            if (!cert.GetKeyUsage()[7])
            {
                Fail("error generating cert - key usage wrong.");
            }

            IList l = cert.GetExtendedKeyUsage();
            if (!l[0].Equals(KeyPurposeID.AnyExtendedKeyUsage.Id))
            {
                Fail("failed extended key usage test");
            }

            foreach (IList gn in cert.GetSubjectAlternativeNames())
            {
                if (!gn[1].Equals("*****@*****.**"))
                {
                    Fail("failed subject alternative names test");
                }
            }

            // Console.WriteLine(cert);

            //
            // create the certificate - version 1
            //
            X509V1CertificateGenerator certGen1 = new X509V1CertificateGenerator();

            certGen1.SetSerialNumber(BigInteger.One);
            certGen1.SetIssuerDN(new X509Name(ord, values));
            certGen1.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
            certGen1.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
            certGen1.SetSubjectDN(new X509Name(ord, values));
            certGen1.SetPublicKey(pubKey);
            certGen1.SetSignatureAlgorithm("MD5WithRSAEncryption");

            cert = certGen1.Generate(privKey);

            cert.CheckValidity(DateTime.UtcNow);

            cert.Verify(pubKey);

            cert = new X509CertificateParser().ReadCertificate(cert.GetEncoded());

            // Console.WriteLine(cert);
            if (!cert.IssuerDN.Equivalent(cert.SubjectDN))
            {
                Fail("name comparison fails");
            }
        }
        /// <summary>
        /// Creates a self signed application instance certificate.
        /// </summary>
        /// <param name="storeType">Type of certificate store (Directory) <see cref="CertificateStoreType"/>.</param>
        /// <param name="storePath">The store path (syntax depends on storeType).</param>
        /// <param name="password">The password to use to protect the certificate.</param>
        /// <param name="applicationUri">The application uri (created if not specified).</param>
        /// <param name="applicationName">Name of the application (optional if subjectName is specified).</param>
        /// <param name="subjectName">The subject used to create the certificate (optional if applicationName is specified).</param>
        /// <param name="domainNames">The domain names that can be used to access the server machine (defaults to local computer name if not specified).</param>
        /// <param name="keySize">Size of the key (1024, 2048 or 4096).</param>
        /// <param name="startTime">The start time.</param>
        /// <param name="lifetimeInMonths">The lifetime of the key in months.</param>
        /// <param name="hashSizeInBits">The hash size in bits.</param>
        /// <param name="isCA">if set to <c>true</c> then a CA certificate is created.</param>
        /// <param name="issuerCAKeyCert">The CA cert with the CA private key.</param>
        /// <returns>The certificate with a private key.</returns>
        public static X509Certificate2 CreateCertificate(
            string storeType,
            string storePath,
            string password,
            string applicationUri,
            string applicationName,
            string subjectName,
            IList<String> domainNames,
            ushort keySize,
            DateTime startTime,
            ushort lifetimeInMonths,
            ushort hashSizeInBits,
            bool isCA,
            X509Certificate2 issuerCAKeyCert)
        {
            if (!String.IsNullOrEmpty(storeType) &&
                storeType != CertificateStoreType.Directory)
            {
                throw new NotSupportedException("Cannot create a certificate for a non directory store.");
            }

            if (issuerCAKeyCert != null)
            {
                if (!issuerCAKeyCert.HasPrivateKey)
                {
                    throw new NotSupportedException("Cannot sign with a CA certificate without a private key.");
                }

                throw new NotSupportedException("Signing with an issuer CA certificate is currently unsupported.");
            }

            // set default values.
            SetSuitableDefaults(
                ref applicationUri,
                ref applicationName,
                ref subjectName,
                ref domainNames,
                ref keySize,
                ref lifetimeInMonths,
                isCA);

            // cert generators
            SecureRandom random = new SecureRandom();
            X509V3CertificateGenerator cg = new X509V3CertificateGenerator();

            // Serial Number
            BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
            cg.SetSerialNumber(serialNumber);

            // build name attributes
            var nameOids = new ArrayList();
            nameOids.Add(X509Name.DC);
            nameOids.Add(X509Name.CN);

            var nameValues = new ArrayList();
            nameValues.Add(domainNames[0]);
            nameValues.Add(applicationName);

            // self signed 
            X509Name subjectDN = new X509Name(nameOids, nameValues);
            X509Name issuerDN = subjectDN;
            cg.SetIssuerDN(issuerDN);
            cg.SetSubjectDN(subjectDN);

            // valid for
            cg.SetNotBefore(startTime);
            cg.SetNotAfter(startTime.AddMonths(lifetimeInMonths));

            // Private/Public Key
            AsymmetricCipherKeyPair subjectKeyPair;
            var keyGenerationParameters = new KeyGenerationParameters(random, keySize);
            var keyPairGenerator = new RsaKeyPairGenerator();
            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();
            cg.SetPublicKey(subjectKeyPair.Public);

            // add extensions
            // Subject key identifier
            cg.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, false,
                new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public)));

            // Basic constraints
            cg.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(isCA));

            // Authority Key identifier
            var issuerKeyPair = subjectKeyPair;
            var issuerSerialNumber = serialNumber;
            cg.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, false,
                new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public),
                    new GeneralNames(new GeneralName(issuerDN)), issuerSerialNumber));

            if (!isCA)
            {
                // Key usage 
                cg.AddExtension(X509Extensions.KeyUsage, true,
                    new KeyUsage(KeyUsage.DataEncipherment | KeyUsage.DigitalSignature |
                        KeyUsage.NonRepudiation | KeyUsage.KeyCertSign | KeyUsage.KeyEncipherment));

                // Extended Key usage
                cg.AddExtension(X509Extensions.ExtendedKeyUsage, true,
                    new ExtendedKeyUsage(new List<DerObjectIdentifier>() {
                    new DerObjectIdentifier("1.3.6.1.5.5.7.3.1"), // server auth
                    new DerObjectIdentifier("1.3.6.1.5.5.7.3.2"), // client auth
                    }));

                // subject alternate name
                cg.AddExtension(X509Extensions.SubjectAlternativeName, false,
                    new GeneralNames(new GeneralName[] {
                    new GeneralName(GeneralName.UniformResourceIdentifier, applicationUri),
                    new GeneralName(GeneralName.DnsName, domainNames[0])}));
            }
            else
            {
                // Key usage CA
                cg.AddExtension(X509Extensions.KeyUsage, true,
                    new KeyUsage(KeyUsage.CrlSign | KeyUsage.DigitalSignature | KeyUsage.KeyCertSign));
            }

            // sign certificate
            ISignatureFactory signatureFactory = 
                new Asn1SignatureFactory((hashSizeInBits < 256) ? "SHA1WITHRSA" : "SHA256WITHRSA", subjectKeyPair.Private, random);
            Org.BouncyCastle.X509.X509Certificate x509 = cg.Generate(signatureFactory);

            // create pkcs12 store for cert and private key
            X509Certificate2 certificate = null;
            using (MemoryStream pfxData = new MemoryStream())
            {
                Pkcs12Store pkcsStore = new Pkcs12StoreBuilder().Build();
                X509CertificateEntry[] chain = new X509CertificateEntry[1];
                string passcode = "passcode";
                chain[0] = new X509CertificateEntry(x509);
                pkcsStore.SetKeyEntry(applicationName, new AsymmetricKeyEntry(subjectKeyPair.Private), chain);
                pkcsStore.Save(pfxData, passcode.ToCharArray(), random);

                // merge into X509Certificate2
                certificate = CreateCertificateFromPKCS12(pfxData.ToArray(), passcode);
            }

            Utils.Trace(Utils.TraceMasks.Security, "Created new certificate: {0}", certificate.Thumbprint);

            // add cert to the store.
            if (!String.IsNullOrEmpty(storePath))
            {
                ICertificateStore store = null;
                if (storeType == CertificateStoreType.Directory)
                {
                    using (store = new DirectoryCertificateStore())
                    {
                        store.Open(storePath);
                        store.Add(certificate);
                        store.Close();
                    }
                }
            }

            // note: this cert has a private key!
            return certificate;
        }
Example #25
0
        /**
         * we Generate a self signed certificate for the sake of testing - ECDSA
         */
        internal void checkCreation3()
        {
            ECCurve curve = new FpCurve(
                new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q
                new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
                new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b

            ECDomainParameters spec = new ECDomainParameters(
                curve,
                curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
                new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n

            ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(
                "ECDSA",
                new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d
                spec);

            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
                "ECDSA",
                curve.DecodePoint(Hex.Decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q
                spec);

            //
            // set up the keys
            //
//			AsymmetricKeyParameter privKey;
//			AsymmetricKeyParameter pubKey;
//
//			try
//			{
//				KeyFactory fact = KeyFactory.GetInstance("ECDSA");
//
//				privKey = fact.generatePrivate(privKeySpec);
//				pubKey = fact.generatePublic(pubKeySpec);
//			}
//			catch (Exception e)
//			{
//				Fail("error setting up keys - " + e.ToString());
//				return;
//			}

            //
            // distinguished name table.
            //
            IDictionary attrs = new Hashtable();
            IList order = new ArrayList();

            attrs.Add(X509Name.C, "AU");
            attrs.Add(X509Name.O, "The Legion of the Bouncy Castle");
            attrs.Add(X509Name.L, "Melbourne");
            attrs.Add(X509Name.ST, "Victoria");
            attrs.Add(X509Name.E, "*****@*****.**");

            order.Add(X509Name.C);
            order.Add(X509Name.O);
            order.Add(X509Name.L);
            order.Add(X509Name.ST);
            order.Add(X509Name.E);


            //
            // ToString test
            //
            X509Name p = new X509Name(order, attrs);
            string s = p.ToString();

            if (!s.Equals("C=AU,O=The Legion of the Bouncy Castle,L=Melbourne,ST=Victoria,[email protected]"))
            {
                Fail("ordered X509Principal test failed - s = " + s + ".");
            }

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

            certGen.SetSerialNumber(BigInteger.One);
            certGen.SetIssuerDN(new X509Name(order, attrs));
            certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
            certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
            certGen.SetSubjectDN(new X509Name(order, attrs));
            certGen.SetPublicKey(pubKey);
            certGen.SetSignatureAlgorithm("SHA1withECDSA");

            try
            {
                X509Certificate cert = certGen.Generate(privKey);

                cert.CheckValidity(DateTime.UtcNow);

                cert.Verify(pubKey);

                X509CertificateParser fact = new X509CertificateParser();
                cert = fact.ReadCertificate(cert.GetEncoded());

                //
                // try with point compression turned off
                //
//				((ECPointEncoder)pubKey).setPointFormat("UNCOMPRESSED");
                ECPoint q = pubKey.Q.Normalize();
                pubKey = new ECPublicKeyParameters(
                    pubKey.AlgorithmName,
                    q.Curve.CreatePoint(q.XCoord.ToBigInteger(), q.YCoord.ToBigInteger()),
                    pubKey.Parameters);

                certGen.SetPublicKey(pubKey);

                cert = certGen.Generate(privKey);

                cert.CheckValidity(DateTime.UtcNow);

                cert.Verify(pubKey);

                cert = fact.ReadCertificate(cert.GetEncoded());

                // Console.WriteLine(cert);
            }
            catch (Exception e)
            {
                Fail("error setting generating cert - " + e.ToString());
            }

            X509Name pr = new X509Name("O=\"The Bouncy Castle, The Legion of\",[email protected],ST=Victoria,L=Melbourne,C=AU");

            if (!pr.ToString().Equals("O=The Bouncy Castle\\, The Legion of,[email protected],ST=Victoria,L=Melbourne,C=AU"))
            {
                Fail("string based X509Principal test failed.");
            }

            pr = new X509Name("O=The Bouncy Castle\\, The Legion of,[email protected],ST=Victoria,L=Melbourne,C=AU");

            if (!pr.ToString().Equals("O=The Bouncy Castle\\, The Legion of,[email protected],ST=Victoria,L=Melbourne,C=AU"))
            {
                Fail("string based X509Principal test failed.");
            }
        }
        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);
        }
Example #27
0
        /**
         * we Generate a self signed certificate for the sake of testing - GOST3410
         */
        internal void checkCreation4()
        {
            //
            // set up the keys
            //
            AsymmetricKeyParameter privKey;
            AsymmetricKeyParameter pubKey;

//			GOST3410ParameterSpec gost3410P = new GOST3410ParameterSpec("GostR3410-94-CryptoPro-A");
//			g.initialize(gost3410P, new SecureRandom());
            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("GOST3410");
            g.Init(
                new Gost3410KeyGenerationParameters(
                    new SecureRandom(),
                    CryptoProObjectIdentifiers.GostR3410x94CryptoProA));

            AsymmetricCipherKeyPair p = g.GenerateKeyPair();

            privKey = p.Private;
            pubKey = p.Public;

            //
            // distinguished name table.
            //
            IDictionary attrs = new Hashtable();
            attrs.Add(X509Name.C, "AU");
            attrs.Add(X509Name.O, "The Legion of the Bouncy Castle");
            attrs.Add(X509Name.L, "Melbourne");
            attrs.Add(X509Name.ST, "Victoria");
            attrs.Add(X509Name.E, "*****@*****.**");

            IList order = new ArrayList();
            order.Add(X509Name.C);
            order.Add(X509Name.O);
            order.Add(X509Name.L);
            order.Add(X509Name.ST);
            order.Add(X509Name.E);

            //
            // extensions
            //

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

            certGen.SetSerialNumber(BigInteger.One);
            certGen.SetIssuerDN(new X509Name(order, attrs));
            certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
            certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
            certGen.SetSubjectDN(new X509Name(order, attrs));
            certGen.SetPublicKey(pubKey);
            certGen.SetSignatureAlgorithm("GOST3411withGOST3410");

            X509Certificate cert = certGen.Generate(privKey);

            cert.CheckValidity(DateTime.UtcNow);

            //
            // check verifies in general
            //
            cert.Verify(pubKey);

            //
            // check verifies with contained key
            //
            cert.Verify(cert.GetPublicKey());

            cert = new X509CertificateParser().ReadCertificate(cert.GetEncoded());

            //Console.WriteLine(cert);

            //check getEncoded()
            byte[] bytesch = cert.GetEncoded();
        }
        /// <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)
        {
            // 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(2000);
            // create the individual store and set two entries for cert and key
            var store = new Pkcs12Store();
            store.SetCertificateEntry("Elastacloud Test Certificate", entry);
            store.SetKeyEntry("Elastacloud Test Certificate", keyEntry, new[] {entry});
            store.Save(stream, userPassword.ToCharArray(), new SecureRandom());

            // Create the equivalent C# representation
            var cert = new X509Certificate2(stream.GetBuffer(), userPassword, X509KeyStorageFlags.Exportable);
            // if specified then this add this certificate to the store
            if (addtoStore)
                AddToMyStore(cert);

            return cert;
        }
Example #29
0
        private void createPssCert(
            string algorithm)
        {
            AsymmetricCipherKeyPair keyPair = GenerateLongFixedKeys();

            AsymmetricKeyParameter privKey = keyPair.Private;
            AsymmetricKeyParameter pubKey = keyPair.Public;

            //
            // distinguished name table.
            //
            IList ord = new ArrayList();
            ord.Add(X509Name.C);
            ord.Add(X509Name.O);
            ord.Add(X509Name.L);
            ord.Add(X509Name.ST);
            ord.Add(X509Name.E);

            IList values = new ArrayList();
            values.Add("AU");
            values.Add("The Legion of the Bouncy Castle");
            values.Add("Melbourne");
            values.Add("Victoria");
            values.Add("*****@*****.**");

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

            certGen.SetSerialNumber(BigInteger.One);
            certGen.SetIssuerDN(new X509Name(ord, values));
            certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
            certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
            certGen.SetSubjectDN(new X509Name(ord, values));
            certGen.SetPublicKey(pubKey);
            certGen.SetSignatureAlgorithm(algorithm);
            certGen.AddExtension("2.5.29.15", true,
            new X509KeyUsage(X509KeyUsage.EncipherOnly));
            certGen.AddExtension("2.5.29.37", true,
            new DerSequence(KeyPurposeID.AnyExtendedKeyUsage));
            certGen.AddExtension("2.5.29.17", true,
            new GeneralNames(new GeneralName(GeneralName.Rfc822Name, "*****@*****.**")));

            X509Certificate baseCert = certGen.Generate(privKey);

            baseCert.Verify(pubKey);
        }
Example #30
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);
        }
Example #31
0
		/**
		* Create a self signed cert for our software emulation
		* 
		* @param kp
		*            is the keypair for our certificate
		* @return a self signed cert for our software emulation
		* @throws InvalidKeyException
		*             on error
		* @throws SignatureException
		*             on error
		*/
		private X509Certificate GenerateSelfSignedSoftECCert(
			AsymmetricCipherKeyPair	kp,
			bool					compress)
		{
			X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
			ECPrivateKeyParameters privECKey = (ECPrivateKeyParameters) kp.Private;
			ECPublicKeyParameters pubECKey = (ECPublicKeyParameters) kp.Public;

			if (!compress)
			{
				// TODO Private key compression?
				//privECKey.setPointFormat("UNCOMPRESSED");
				//pubECKey.setPointFormat("UNCOMPRESSED");
				pubECKey = SetPublicUncompressed(pubECKey);
			}

			certGen.SetSignatureAlgorithm("ECDSAwithSHA1");
			certGen.SetSerialNumber(BigInteger.One);
			certGen.SetIssuerDN(new X509Name("CN=Software emul (EC Cert)"));
			certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
			certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50000));
			certGen.SetSubjectDN(new X509Name("CN=Software emul (EC Cert)"));
			certGen.SetPublicKey(pubECKey);

			return certGen.Generate(privECKey);
		}
        /// <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;
        }