public static X509Certificate MakeV1Certificate(AsymmetricCipherKeyPair subKP, string _subDN, AsymmetricCipherKeyPair issKP, string _issDN) { AsymmetricKeyParameter subPub = subKP.Public; AsymmetricKeyParameter issPriv = issKP.Private; AsymmetricKeyParameter issPub = issKP.Public; X509V1CertificateGenerator v1CertGen = new X509V1CertificateGenerator(); v1CertGen.Reset(); v1CertGen.SetSerialNumber(AllocateSerialNumber()); v1CertGen.SetIssuerDN(new X509Name(_issDN)); v1CertGen.SetNotBefore(DateTime.UtcNow); v1CertGen.SetNotAfter(DateTime.UtcNow.AddDays(100)); v1CertGen.SetSubjectDN(new X509Name(_subDN)); v1CertGen.SetPublicKey(subPub); if (issPub is RsaKeyParameters) { v1CertGen.SetSignatureAlgorithm("SHA1WithRSA"); } else if (issPub is DsaPublicKeyParameters) { v1CertGen.SetSignatureAlgorithm("SHA1withDSA"); } else if (issPub is ECPublicKeyParameters) { ECPublicKeyParameters ecPub = (ECPublicKeyParameters)issPub; if (ecPub.AlgorithmName == "ECGOST3410") { v1CertGen.SetSignatureAlgorithm("GOST3411withECGOST3410"); } else { v1CertGen.SetSignatureAlgorithm("SHA1withECDSA"); } } else { v1CertGen.SetSignatureAlgorithm("GOST3411WithGOST3410"); } X509Certificate _cert = v1CertGen.Generate(issPriv); _cert.CheckValidity(DateTime.UtcNow); _cert.Verify(issPub); return(_cert); }
public static X509Certificate GenerateRootCert( IAsymmetricCipherKeyPair pair) { X509V1CertificateGenerator certGen = new X509V1CertificateGenerator(); certGen.SetSerialNumber(BigInteger.One); certGen.SetIssuerDN(new X509Name("CN=Test CA Certificate")); certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50)); certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50)); certGen.SetSubjectDN(new X509Name("CN=Test CA Certificate")); certGen.SetPublicKey(pair.Public); certGen.SetSignatureAlgorithm("SHA256WithRSAEncryption"); return(certGen.Generate(pair.Private)); }
/// <summary> /// Generates client certificate by certificate signing request. /// </summary> /// <param name="csrBytes">CSR as bytes array</param> /// <param name="commonName">Common name of certificate</param> /// <exception cref="InvalidCastException">Invalid format of CSR</exception> /// <returns></returns> public static X509Certificate2 SignRequest(byte[] csrBytes, string commonName) { if (string.IsNullOrEmpty(commonName)) { throw new ArgumentNullException("commonName"); } var certificationRequest = new Pkcs10CertificationRequest(csrBytes); CertificationRequestInfo csrInfo = certificationRequest.GetCertificationRequestInfo(); SubjectPublicKeyInfo pki = csrInfo.SubjectPublicKeyInfo; AsymmetricKeyParameter publicKey = PublicKeyFactory.CreateKey(pki); // Version1 (No Extensions) Certificate DateTime startDate = DateTime.UtcNow; DateTime expiryDate = startDate.AddYears(100); var serialNumber = new BigInteger(32, new Random()); var certGen = new X509V1CertificateGenerator(); var x509ServerCertificate = ServerCertificate; var caCert = DotNetUtilities.FromX509Certificate(x509ServerCertificate); certGen.SetSerialNumber(serialNumber); certGen.SetIssuerDN(caCert.SubjectDN); certGen.SetNotBefore(startDate); certGen.SetNotAfter(expiryDate); certGen.SetSubjectDN(CreateSubject(commonName)); certGen.SetSignatureAlgorithm("SHA256withRSA"); certGen.SetPublicKey(publicKey); var keyPath = string.Format(@"{0}\App_Data\server.key", AppDomain.CurrentDomain.BaseDirectory); AsymmetricCipherKeyPair keyPair; using (var reader = File.OpenText(keyPath)) { keyPair = (AsymmetricCipherKeyPair) new PemReader(reader, new PasswordFinder()).ReadObject(); } Org.BouncyCastle.X509.X509Certificate cert = certGen.Generate(keyPair.Private); return(new X509Certificate2(DotNetUtilities.ToX509Certificate(cert))); }
private Org.BouncyCastle.X509.X509Certificate CreateCertificate(string issuerName, string subjectName) { var random = new SecureRandom(); var generator = new X509V1CertificateGenerator(); var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random); generator.SetSerialNumber(serialNumber); var privateKey = GetPrivateRsaAsymmetricKeyParameter(); var publicKey = GetPublicRsaAsymmetricKeyParameter(); var asn1SignatureFactory = new Asn1SignatureFactory(PkcsObjectIdentifiers.Sha1WithRsaEncryption.Id, privateKey, random); generator.SetPublicKey(publicKey); var subjectDN = new X509Name(subjectName); generator.SetSubjectDN(subjectDN); var issuerDN = new X509Name(issuerName); generator.SetIssuerDN(issuerDN); generator.SetNotAfter(DateTime.UtcNow.AddYears(10)); generator.SetNotBefore(DateTime.UtcNow.AddYears(-1)); // var authorityKeyIdentifier = new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey), new GeneralNames(new GeneralName(issuerDN)), serialNumber); // var subjectKeyIdentidifer = new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey)); // generator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, authorityKeyIdentifier); // generator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, subjectKeyIdentidifer); // generator.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(0)); var cert = generator.Generate(asn1SignatureFactory); cert.CheckValidity(DateTime.UtcNow); cert.Verify(publicKey); return(cert); }
public static byte[] GenerateRootCertificate(string certName, string Password, out byte[] PlainCer) { PlainCer = null; X509V1CertificateGenerator certGen = new X509V1CertificateGenerator(); X509Name CN = new X509Name("CN=" + certName); RsaKeyPairGenerator keypairgen = new RsaKeyPairGenerator(); keypairgen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 2048)); AsymmetricCipherKeyPair keypair = keypairgen.GenerateKeyPair(); certGen.SetSerialNumber(BigInteger.ProbablePrime(120, new Random())); certGen.SetIssuerDN(CN); certGen.SetNotAfter(new DateTime(2099, 1, 1)); certGen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0))); certGen.SetSubjectDN(CN); certGen.SetPublicKey(keypair.Public); CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator(); SecureRandom random = new SecureRandom(randomGenerator); ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", keypair.Private, random); Org.BouncyCastle.X509.X509Certificate newCert = certGen.Generate(signatureFactory); Pkcs12Store pkcs = new Pkcs12Store(); pkcs.SetCertificateEntry(certName, new X509CertificateEntry(newCert)); AsymmetricKeyEntry keyentry = new AsymmetricKeyEntry(keypair.Private); pkcs.SetKeyEntry(certName, keyentry, new[] { new X509CertificateEntry(newCert) }); MemoryStream mem = new MemoryStream(); pkcs.Save(mem, Password.ToCharArray(), random); PlainCer = newCert.GetEncoded(); return(mem.GetBuffer()); }
/// <exception cref="CertificateEncodingException"/> /// <exception cref="InvalidKeyException"/> /// <exception cref="System.InvalidOperationException"/> /// <exception cref="NoSuchProviderException"/> /// <exception cref="NoSuchAlgorithmException"/> /// <exception cref="SignatureException"/> public static X509Certificate GenerateCertificate(string dn, KeyPair pair , int days, string algorithm) { DateTime from = new DateTime(); DateTime to = Extensions.CreateDate(from.GetTime() + days * 86400000l); BigInteger sn = new BigInteger(64, new SecureRandom()); KeyPair keyPair = pair; X509V1CertificateGenerator certGen = new X509V1CertificateGenerator(); X500Principal dnName = new X500Principal(dn); certGen.SetSerialNumber(sn); certGen.SetIssuerDN(dnName); certGen.SetNotBefore(from); certGen.SetNotAfter(to); certGen.SetSubjectDN(dnName); certGen.SetPublicKey(keyPair.GetPublic()); certGen.SetSignatureAlgorithm(algorithm); X509Certificate cert = certGen.Generate(pair.GetPrivate()); return(cert); }
public static Org.BouncyCastle.X509.X509Certificate generateRootCertV2(string certName) { X509V1CertificateGenerator certGen = new X509V1CertificateGenerator(); X509Name CN = new X509Name("CN=" + certName); RsaKeyPairGenerator keypairgen = new RsaKeyPairGenerator(); keypairgen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 1024)); AsymmetricCipherKeyPair keypair = keypairgen.GenerateKeyPair(); certGen.SetSerialNumber(BigInteger.ProbablePrime(120, new Random())); certGen.SetIssuerDN(CN); certGen.SetNotAfter(DateTime.MaxValue); certGen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0))); certGen.SetSubjectDN(CN); certGen.SetPublicKey(keypair.Public); certGen.SetSignatureAlgorithm("MD5WithRSA"); Org.BouncyCastle.X509.X509Certificate newCert = certGen.Generate(keypair.Private); return(newCert); }
public static (AsymmetricCipherKeyPair, X509Certificate) GenerateSelfSigned() { var startDate = DateTime.Now; var expiryDate = DateTime.Now.AddYears(10); var serialNumber = BigIntegers.CreateRandomInRange( BigInteger.ValueOf(2).Pow(63), BigInteger.ValueOf(2).Pow(64), new SecureRandom() ); var oid = ECGost3410NamedCurves.GetOid("Tc26-Gost-3410-12-256-paramSetA"); var param = new ECKeyGenerationParameters(oid, new SecureRandom()); var engine = new ECKeyPairGenerator(); engine.Init(param); var keyPair = engine.GenerateKeyPair(); var certGen = new X509V1CertificateGenerator(); var dnName = new X509Name("CN=Test CA Certificate"); certGen.SetSerialNumber(serialNumber); certGen.SetIssuerDN(dnName); certGen.SetNotBefore(startDate); certGen.SetNotAfter(expiryDate); certGen.SetSubjectDN(dnName); certGen.SetPublicKey(keyPair.Public); var signer = new GostSignerFactory(keyPair.Private); var certificate = certGen.Generate(signer); return(keyPair, certificate); }
static void Main(string[] args) { char[] passwd = "123456".ToCharArray(); //pfx密码 IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("RSA"); RsaKeyGenerationParameters genPar = new RsaKeyGenerationParameters( BigInteger.ValueOf(0x10001), new SecureRandom(), 2048, 25); keyGen.Init(genPar); AsymmetricCipherKeyPair keypair = keyGen.GenerateKeyPair(); RsaKeyParameters pubKey = (RsaKeyParameters)keypair.Public; //CA公钥 RsaKeyParameters priKey = (RsaKeyParameters)keypair.Private; //CA私钥 Hashtable attrs = new Hashtable(); ArrayList order = new ArrayList(); attrs.Add(X509Name.C, "CN"); //country code //attrs.Add(X509Name.ST, "Guangdong province"); //province name //attrs.Add(X509Name.L, "Guangzhou city"); //locality name attrs.Add(X509Name.O, "South China Normal University"); //organization attrs.Add(X509Name.OU, "South China Normal University"); //organizational unit name attrs.Add(X509Name.CN, "CAcert"); //common name attrs.Add(X509Name.E, "*****@*****.**"); order.Add(X509Name.C); //order.Add(X509Name.ST); //order.Add(X509Name.L); order.Add(X509Name.O); order.Add(X509Name.OU); order.Add(X509Name.CN); order.Add(X509Name.E); X509Name issuerDN = new X509Name(order, attrs); X509Name subjectDN = issuerDN; //自签证书,两者一样 X509V1CertificateGenerator v1certGen = new X509V1CertificateGenerator(); v1certGen.SetSerialNumber(new BigInteger(128, new Random())); //128位 v1certGen.SetIssuerDN(issuerDN); v1certGen.SetNotBefore(DateTime.UtcNow.AddDays(-1)); v1certGen.SetNotAfter(DateTime.UtcNow.AddDays(365)); v1certGen.SetSubjectDN(subjectDN); v1certGen.SetPublicKey(pubKey); //公钥 v1certGen.SetSignatureAlgorithm("SHA1WithRSAEncryption"); Org.BouncyCastle.X509.X509Certificate CAcert = v1certGen.Generate(priKey); CAcert.CheckValidity(); CAcert.Verify(pubKey); //属性包 /* * Hashtable bagAttr = new Hashtable(); * bagAttr.Add(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id, * new DerBmpString("CA's Primary Certificate")); * bagAttr.Add(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Id, * new SubjectKeyIdentifierStructure(pubKey)); * * X509CertificateEntry certEntry = new X509CertificateEntry(CAcert,bagAttr); */ X509CertificateEntry certEntry = new X509CertificateEntry(CAcert); Pkcs12Store store = new Pkcs12StoreBuilder().Build(); store.SetCertificateEntry("CA's Primary Certificate", certEntry); //设置证书 X509CertificateEntry[] chain = new X509CertificateEntry[1]; chain[0] = certEntry; store.SetKeyEntry("CA's Primary Certificate", new AsymmetricKeyEntry(priKey), chain); //设置私钥 FileStream fout = File.Create("CA.pfx"); store.Save(fout, passwd, new SecureRandom()); //保存 fout.Close(); }
private void cmdOK_Click(object sender, EventArgs e) { X509V1CertificateGenerator certGen = new X509V1CertificateGenerator(); IDictionary attrs = new Hashtable(); attrs[X509Name.CN] = txtCN.Text; attrs[X509Name.O] = txtCompany.Text; attrs[X509Name.C] = txtCC.Text; attrs[X509Name.ST] = txtProvince.Text; attrs[X509Name.OU] = txtOU.Text; attrs[X509Name.L] = txtCity.Text; IList ord = new ArrayList(); ord.Add(X509Name.CN); ord.Add(X509Name.O); ord.Add(X509Name.C); ord.Add(X509Name.ST); ord.Add(X509Name.OU); ord.Add(X509Name.L); X509Name CN = new X509Name(ord, attrs); Org.BouncyCastle.X509.X509Certificate newCert; certGen.SetSerialNumber(BigInteger.ProbablePrime(120, new Random())); certGen.SetIssuerDN(CN); certGen.SetNotAfter(new DateTime(DT.Value.Year, DT.Value.Month, DT.Value.Day, 0, 0, 0, 0)); certGen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0))); certGen.SetSubjectDN(CN); CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator(); SecureRandom random; AsymmetricCipherKeyPair keypair; if (txtSPKI.Text == "") { RsaKeyPairGenerator keypairgen = new RsaKeyPairGenerator(); keypairgen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 2048)); keypair = keypairgen.GenerateKeyPair(); certGen.SetPublicKey(keypair.Public); random = new SecureRandom(randomGenerator); ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", keypair.Private, random); newCert = certGen.Generate(signatureFactory); } else { RsaPublicKeyStructure rsaPubStructure = RsaPublicKeyStructure.GetInstance(Asn1Object.FromByteArray(File.ReadAllBytes(txtSPKI.Text))); AsymmetricKeyParameter extpublickey = (AsymmetricKeyParameter)(new RsaKeyParameters(false, rsaPubStructure.Modulus, rsaPubStructure.PublicExponent)); certGen.SetPublicKey(extpublickey); RsaKeyPairGenerator keypairgen = new RsaKeyPairGenerator(); keypairgen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 2048)); keypair = keypairgen.GenerateKeyPair(); random = new SecureRandom(randomGenerator); ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", keypair.Private, random); newCert = certGen.Generate(signatureFactory); } byte[] PlainCer = newCert.GetEncoded(); SaveFileDialog save = new SaveFileDialog(); if (lstOutput.SelectedIndex == 0) { save.Filter = "Certificate|*.cer"; save.DefaultExt = ".cer"; save.Title = "Save CER file"; } if (lstOutput.SelectedIndex == 1) { save.Filter = "Certificate|*.der"; save.DefaultExt = ".der"; save.Title = "Save DER file"; } if (lstOutput.SelectedIndex == 2) { save.Filter = "Certificate|*.p12"; save.DefaultExt = ".p12"; save.Title = "Save P12 file"; } if (save.ShowDialog(this) != System.Windows.Forms.DialogResult.OK) { return; } if (lstOutput.SelectedIndex == 0) { File.WriteAllBytes(save.FileName, PlainCer); } if (lstOutput.SelectedIndex == 1) { TextWriter txt = new StreamWriter(save.FileName, false, Encoding.ASCII); PemWriter text = new PemWriter(txt); text.WriteObject(newCert); txt.Close(); } if (lstOutput.SelectedIndex == 2) { Pkcs12Store pkcs = new Pkcs12Store(); pkcs.SetCertificateEntry(txtCN.Text, new X509CertificateEntry(newCert)); AsymmetricKeyEntry keyentry = new AsymmetricKeyEntry(keypair.Private); pkcs.SetKeyEntry(txtCN.Text, keyentry, new[] { new X509CertificateEntry(newCert) }); MemoryStream mem = new MemoryStream(); pkcs.Save(mem, txtPassword.Text.ToCharArray(), random); PlainCer = newCert.GetEncoded(); File.WriteAllBytes(save.FileName, mem.GetBuffer()); } this.Close(); }