/// <summary> /// Create a self signed certificate. /// </summary> public static X509Certificate2 GenerateCertificate( string subjectName, AsymmetricCipherKeyPair keyPair) { if (string.IsNullOrEmpty(subjectName)) { subjectName = "NuGetTest"; } var certGen = new X509V3CertificateGenerator(); certGen.SetSubjectDN(new X509Name($"CN={subjectName}")); certGen.SetIssuerDN(new X509Name($"CN={subjectName}")); certGen.SetNotAfter(DateTime.UtcNow.Add(TimeSpan.FromHours(1))); certGen.SetNotBefore(DateTime.UtcNow.Subtract(TimeSpan.FromHours(1))); certGen.SetPublicKey(keyPair.Public); var random = new SecureRandom(); var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random); certGen.SetSerialNumber(serialNumber); var subjectKeyIdentifier = new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public)); certGen.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, false, subjectKeyIdentifier); certGen.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.KeyCertSign)); certGen.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(false)); var usages = new[] { KeyPurposeID.IdKPCodeSigning }; certGen.AddExtension( X509Extensions.ExtendedKeyUsage.Id, critical: true, extensionValue: new ExtendedKeyUsage(usages)); var issuerPrivateKey = keyPair.Private; var signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", issuerPrivateKey, random); var certificate = certGen.Generate(signatureFactory); var certResult = new X509Certificate2(certificate.GetEncoded()); #if IS_DESKTOP certResult.PrivateKey = DotNetUtilities.ToRSA(keyPair.Private as RsaPrivateCrtKeyParameters); #endif return(certResult); }
public static void GenerateNewCertificate(string name, Stream stream) { 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 } ); newStore.Save( stream, new char[0], new SecureRandom(new CryptoApiRandomGenerator()) ); }
public static X509Certificate2 GenerateSelfSignedCertificate(string domain, DateTime?dateFrom = null, DateTime?dateTo = null) { // configure generators var random = new SecureRandom(new CryptoApiRandomGenerator()); var keyGenerationParameters = new KeyGenerationParameters(random, 2048); var keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); // create self-signed certificate var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random); var certificateGenerator = new X509V3CertificateGenerator(); certificateGenerator.SetSubjectDN(new X509Name($"CN={domain}")); certificateGenerator.SetIssuerDN(new X509Name($"CN={domain}")); certificateGenerator.SetSerialNumber(serialNumber); certificateGenerator.SetNotBefore(dateFrom ?? DateTime.UtcNow); certificateGenerator.SetNotAfter(dateTo ?? DateTime.UtcNow.AddMinutes(5)); certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName.Id, false, new DerSequence(new Asn1Encodable[] { new GeneralName(GeneralName.DnsName, domain) })); certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeID[] { KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPClientAuth })); certificateGenerator.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.KeyEncipherment | KeyUsage.DigitalSignature)); var keyPair = keyPairGenerator.GenerateKeyPair(); certificateGenerator.SetPublicKey(keyPair.Public); var bouncy_cert = certificateGenerator.Generate(new Asn1SignatureFactory("SHA256WithRSA", keyPair.Private, random)); // get private key into machine key store var csp = new RSACryptoServiceProvider( new CspParameters { KeyContainerName = Guid.NewGuid().ToString(), KeyNumber = 1, Flags = CspProviderFlags.UseMachineKeyStore }); var rp = DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters)keyPair.Private); csp.ImportParameters(rp); // convert from bouncy cert to X509Certificate2 return(new X509Certificate2(bouncy_cert.GetEncoded(), (string)null, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet) { FriendlyName = domain + " [Certify] Self Signed - " + bouncy_cert.NotBefore + " to " + bouncy_cert.NotAfter, PrivateKey = csp }); }
public void TestX509CertificateConversion() { BigInteger DSAParaG = new BigInteger(Base64.Decode("AL0fxOTq10OHFbCf8YldyGembqEu08EDVzxyLL29Zn/t4It661YNol1rnhPIs+cirw+yf9zeCe+KL1IbZ/qIMZM=")); BigInteger DSAParaP = new BigInteger(Base64.Decode("AM2b/UeQA+ovv3dL05wlDHEKJ+qhnJBsRT5OB9WuyRC830G79y0R8wuq8jyIYWCYcTn1TeqVPWqiTv6oAoiEeOs=")); BigInteger DSAParaQ = new BigInteger(Base64.Decode("AIlJT7mcKL6SUBMmvm24zX1EvjNx")); BigInteger DSAPublicY = new BigInteger(Base64.Decode("TtWy2GuT9yGBWOHi1/EpCDa/bWJCk2+yAdr56rAcqP0eHGkMnA9s9GJD2nGU8sFjNHm55swpn6JQb8q0agrCfw==")); BigInteger 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); }
public CertGenerator(double days = 0) { _certificateGenerator = new X509V3CertificateGenerator(); _certificateGenerator.SetSignatureAlgorithm(_signatureAlgorithm); var subjectDn = new X509Name("CN=" + DefaultSubjectName); var issuerDn = new X509Name("CN=" + DefaultSubjectName); _certificateGenerator.SetIssuerDN(issuerDn); _certificateGenerator.SetSubjectDN(subjectDn); var notBefore = DateTime.UtcNow.Date; var notAfter = notBefore.AddDays(Math.Abs(days) >= 1 ?days : DefautIntervalDays); _certificateGenerator.SetNotBefore(notBefore); _certificateGenerator.SetNotAfter(notAfter); _certificateGenerator.SetSerialNumber(BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random)); }
public static X509Certificate2 GenerateCertificate(string subject) { var random = new SecureRandom(); var certificateGenerator = new X509V3CertificateGenerator(); var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random); certificateGenerator.SetSerialNumber(serialNumber); certificateGenerator.SetIssuerDN(new X509Name($"C=DE, O=MakroBoard, CN={subject}")); certificateGenerator.SetSubjectDN(new X509Name($"C=DE, O=MakroBoard, CN={subject}")); certificateGenerator.SetNotBefore(DateTime.UtcNow.Date); certificateGenerator.SetNotAfter(DateTime.UtcNow.Date.AddYears(1)); const int strength = 2048; var keyGenerationParameters = new KeyGenerationParameters(random, strength); var keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); var subjectKeyPair = keyPairGenerator.GenerateKeyPair(); certificateGenerator.SetPublicKey(subjectKeyPair.Public); var issuerKeyPair = subjectKeyPair; const string signatureAlgorithm = "SHA256WithRSA"; var signatureFactory = new Asn1SignatureFactory(signatureAlgorithm, issuerKeyPair.Private); var bouncyCert = certificateGenerator.Generate(signatureFactory); // Lets convert it to X509Certificate2 X509Certificate2 certificate; Pkcs12Store store = new Pkcs12StoreBuilder().Build(); store.SetKeyEntry($"{subject}_key", new AsymmetricKeyEntry(subjectKeyPair.Private), new[] { new X509CertificateEntry(bouncyCert) }); string exportpw = Guid.NewGuid().ToString("x"); using (var ms = new System.IO.MemoryStream()) { store.Save(ms, exportpw.ToCharArray(), random); certificate = new X509Certificate2(ms.ToArray(), exportpw, X509KeyStorageFlags.Exportable); } //Console.WriteLine($"Generated cert with thumbprint {certificate.Thumbprint}"); return(certificate); }
public static X509Certificate GenerateCertificate(X509Name issuer, X509Name subject, AsymmetricKeyParameter issuerPrivate, AsymmetricKeyParameter subjectPublic) { ISignatureFactory signatureFactory = new Asn1SignatureFactory( PkcsObjectIdentifiers.Sha256WithRsaEncryption.ToString(), issuerPrivate); var certGenerator = new X509V3CertificateGenerator(); certGenerator.SetIssuerDN(issuer); certGenerator.SetSubjectDN(subject); certGenerator.SetSerialNumber(BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), new SecureRandom())); certGenerator.SetNotBefore(DateTime.UtcNow.Date); certGenerator.SetNotAfter(DateTime.MaxValue); certGenerator.SetPublicKey(subjectPublic); return(certGenerator.Generate(signatureFactory)); }
static X509Certificate2 AttemptToGenerate(string fullName) { var kpgen = new RsaKeyPairGenerator(); kpgen.Init(new KeyGenerationParameters(Random, 2048)); var cerKp = kpgen.GenerateKeyPair(); IDictionary attrs = new Hashtable(); attrs[X509Name.E] = ""; attrs[X509Name.CN] = fullName; attrs[X509Name.O] = fullName; attrs[X509Name.C] = fullName; IList ord = new ArrayList(); ord.Add(X509Name.E); ord.Add(X509Name.CN); ord.Add(X509Name.O); ord.Add(X509Name.C); var certGen = new X509V3CertificateGenerator(); var serial = new byte[32]; Random.NextBytes(serial); certGen.SetSerialNumber(new BigInteger(serial).Abs()); certGen.SetIssuerDN(new X509Name(ord, attrs)); certGen.SetNotBefore(DateTime.Today.Subtract(new TimeSpan(1, 0, 0, 0))); certGen.SetNotAfter(DateTime.Today.AddYears(100)); certGen.SetSubjectDN(new X509Name(ord, attrs)); certGen.SetPublicKey(cerKp.Public); certGen.SetSignatureAlgorithm("SHA1WithRSA"); certGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, true, new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(cerKp.Public))); var x509 = certGen.Generate(cerKp.Private); var x509Certificate = DotNetUtilities.ToX509Certificate(x509); return(new X509Certificate2(x509Certificate) { PrivateKey = AddPrivateKey(cerKp) }); }
internal static X509Certificate2 BuildRootCertificate() { var name = "!!! PassiveX Root CA !!!"; var random = new SecureRandom(); var keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(new KeyGenerationParameters(random, KeyStrength)); var subjectKeyPair = keyPairGenerator.GenerateKeyPair(); var certificateGenerator = new X509V3CertificateGenerator(); var serialNumber = BigInteger.ProbablePrime(120, random); certificateGenerator.SetSerialNumber(serialNumber); certificateGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); certificateGenerator.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.KeyCertSign | KeyUsage.CrlSign)); certificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public))); certificateGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public))); certificateGenerator.SetIssuerDN(new X509Name($"CN={name}")); certificateGenerator.SetSubjectDN(new X509Name($"CN={name}")); var notBefore = new DateTime(2000, 01, 01); var notAfter = new DateTime(2039, 12, 31); certificateGenerator.SetNotBefore(notBefore); certificateGenerator.SetNotAfter(notAfter); certificateGenerator.SetPublicKey(subjectKeyPair.Public); var signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", subjectKeyPair.Private, random); var x509 = certificateGenerator.Generate(signatureFactory); var certificate = new X509Certificate2(x509.GetEncoded()); certificate.PrivateKey = DotNetUtilities.ToRSA((RsaPrivateCrtKeyParameters)subjectKeyPair.Private); certificate.FriendlyName = name; return(certificate); }
/// <summary> /// /// </summary> /// <param name="domains"></param> /// <param name="subjectPublic"></param> /// <param name="validFrom"></param> /// <param name="validTo"></param> /// <param name="issuerName"></param> /// <param name="issuerPublic"></param> /// <param name="issuerPrivate"></param> /// <param name="CA_PathLengthConstraint">If non-null, the certificate will be marked as a certificate authority with the specified path length constraint (0 to allow no child certificate authorities, 1 to allow 1, etc).</param> /// <returns></returns> private static X509Certificate GenerateCertificate(string[] domains, AsymmetricKeyParameter subjectPublic, DateTime validFrom, DateTime validTo, string issuerName, AsymmetricKeyParameter issuerPublic, AsymmetricKeyParameter issuerPrivate, int?CA_PathLengthConstraint) { ISignatureFactory signatureFactory; if (issuerPrivate is ECPrivateKeyParameters) { signatureFactory = new Asn1SignatureFactory( X9ObjectIdentifiers.ECDsaWithSha256.ToString(), issuerPrivate); } else { signatureFactory = new Asn1SignatureFactory( PkcsObjectIdentifiers.Sha256WithRsaEncryption.ToString(), issuerPrivate); } X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator(); certGenerator.SetIssuerDN(new X509Name("CN=" + issuerName)); certGenerator.SetSubjectDN(new X509Name("CN=" + domains[0])); certGenerator.SetSerialNumber(BigInteger.ProbablePrime(120, new Random())); certGenerator.SetNotBefore(validFrom); certGenerator.SetNotAfter(validTo); certGenerator.SetPublicKey(subjectPublic); if (issuerPublic != null) { AuthorityKeyIdentifierStructure akis = new AuthorityKeyIdentifierStructure(issuerPublic); certGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, akis); } if (CA_PathLengthConstraint != null && CA_PathLengthConstraint >= 0) { X509Extension extension = new X509Extension(true, new DerOctetString(new BasicConstraints(CA_PathLengthConstraint.Value))); certGenerator.AddExtension(X509Extensions.BasicConstraints, extension.IsCritical, extension.GetParsedValue()); } // Add SANs (Subject Alternative Names) GeneralName[] names = domains.Select(domain => new GeneralName(GeneralName.DnsName, domain)).ToArray(); GeneralNames subjectAltName = new GeneralNames(names); certGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false, subjectAltName); return(certGenerator.Generate(signatureFactory)); }
private void keyStoreTest( IAsymmetricKeyParameter sKey, IAsymmetricKeyParameter vKey) // throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, NoSuchProviderException, SignatureException, InvalidKeyException, UnrecoverableKeyException { // // keystore test // // KeyStore ks = KeyStore.GetInstance("JKS"); // ks.Load(null, null); Pkcs12StoreBuilder ksBuilder = new Pkcs12StoreBuilder(); Pkcs12Store ks = ksBuilder.Build(); // // create the certificate - version 3 // 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(vKey); certGen.SetSignatureAlgorithm("GOST3411withGOST3410"); X509Certificate cert = certGen.Generate(sKey); X509CertificateEntry certEntry = new X509CertificateEntry(cert); // ks.SetKeyEntry("gost", sKey, "gost".ToCharArray(), new X509Certificate[] { cert }); ks.SetKeyEntry("gost", new AsymmetricKeyEntry(sKey), new X509CertificateEntry[] { certEntry }); MemoryStream bOut = new MemoryStream(); ks.Save(bOut, "gost".ToCharArray(), new SecureRandom()); // ks = KeyStore.getInstance("JKS"); ks = ksBuilder.Build(); ks.Load(new MemoryStream(bOut.ToArray(), false), "gost".ToCharArray()); // IAsymmetricKeyParameter gKey = (AsymmetricKeyParameter)ks.GetKey("gost", "gost".ToCharArray()); // AsymmetricKeyEntry gKeyEntry = (AsymmetricKeyEntry) ks.GetKey("gost"); }
/// <summary> /// Generates a self signed certificate for this store to be able to issue cloned certs. /// </summary> private void GenerateSelfSignedCertificate() { var kpg = new ECKeyPairGenerator(); kpg.Init(new KeyGenerationParameters(new SecureRandom(), 256)); m_caKeypair = kpg.GenerateKeyPair(); m_caSigner = new Asn1SignatureFactory("SHA256withECDSA", m_caKeypair.Private); DateTime startDate = DateTime.Now.AddYears(-1).ToUniversalTime(); DateTime expiryDate = DateTime.Now.AddYears(2).ToUniversalTime(); BigInteger serialNumber = BigInteger.ProbablePrime(256, new Random()); var certGen = new X509V3CertificateGenerator(); /* * var certificatePermissions = new List<KeyPurposeID>() * { * KeyPurposeID.IdKPCodeSigning, * KeyPurposeID.IdKPServerAuth, * KeyPurposeID.IdKPTimeStamping, * KeyPurposeID.IdKPOcspSigning, * KeyPurposeID.IdKPClientAuth * }; */ X509Name dnName = new X509Name("CN=Citadel Core"); certGen.SetSerialNumber(serialNumber); certGen.SetIssuerDN(dnName); certGen.SetNotBefore(startDate); certGen.SetNotAfter(expiryDate); //certGen.AddExtension(Org.BouncyCastle.Asn1.X509.X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(certificatePermissions)); certGen.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(m_caKeypair.Public)); certGen.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.CrlSign | KeyUsage.KeyCertSign)); certGen.AddExtension(Org.BouncyCastle.Asn1.X509.X509Extensions.BasicConstraints, false, new BasicConstraints(true)); // Note that because we're self signing, our subject and issuer names are the same. certGen.SetSubjectDN(dnName); certGen.SetPublicKey(m_caKeypair.Public); m_caCertificate = certGen.Generate(m_caSigner); }
public static X509Certificate GenerateCertificate(X509Name issuer, X509Name subject, AsymmetricKeyParameter issuerPrivate, AsymmetricKeyParameter subjectPublic, DateTime?notBefore = null, DateTime?notAfter = null) { ISignatureFactory signatureFactory = new Asn1SignatureFactory( PkcsObjectIdentifiers.Sha256WithRsaEncryption.ToString(), issuerPrivate); X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator(); certGenerator.SetIssuerDN(issuer); certGenerator.SetSubjectDN(subject); certGenerator.SetSerialNumber(BigInteger.ValueOf(Math.Abs(secureRandom.NextInt()))); certGenerator.SetNotAfter(notAfter ?? DateTime.UtcNow.AddHours(1)); certGenerator.SetNotBefore(notBefore ?? DateTime.UtcNow); certGenerator.SetPublicKey(subjectPublic); certGenerator.AddExtension(Org.BouncyCastle.Asn1.X509.X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyCertSign | KeyUsage.CrlSign)); certGenerator.AddExtension(Org.BouncyCastle.Asn1.X509.X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeID.IdKPTimeStamping)); return(certGenerator.Generate(signatureFactory)); }
private static X509Certificate CreateX509Certificate(X509Certificate2 certificate, AsymmetricKeyParameter publicKeyParameters, AsymmetricKeyParameter privateKeyParameters) { var constructor = new X509V3CertificateGenerator(); constructor.SetSerialNumber(new BigInteger(certificate.GetSerialNumber().Reverse().ToArray())); constructor.SetSubjectDN(new X509Name("CN=DoNotTrust, C=Denmark")); constructor.SetIssuerDN(new X509Name("CN=DoNotTrust, C=Denmark")); constructor.SetNotBefore(DateTime.Now); constructor.SetNotAfter(DateTime.Now.Add(TimeSpan.FromDays(3650))); constructor.SetPublicKey(publicKeyParameters); constructor.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.KeyCertSign | KeyUsage.CrlSign)); constructor.AddExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(true)); var signatureFactory = new Asn1SignatureFactory(certificate.SignatureAlgorithm.Value, privateKeyParameters); var newCertificate = constructor.Generate(signatureFactory); return(newCertificate); }
private byte[] gen() { TextReader textReader = new StreamReader("certificaterequest.pkcs10"); PemReader pemReader = new PemReader(textReader); Pkcs10CertificationRequest certificationRequest = (Pkcs10CertificationRequest)pemReader.ReadObject(); CertificationRequestInfo certificationRequestInfo = certificationRequest.GetCertificationRequestInfo(); SubjectPublicKeyInfo publicKeyInfo = certificationRequestInfo.SubjectPublicKeyInfo; RsaPublicKeyStructure publicKeyStructure = RsaPublicKeyStructure.GetInstance(publicKeyInfo.GetPublicKey()); RsaKeyParameters publicKey = new RsaKeyParameters(false, publicKeyStructure.Modulus, publicKeyStructure.PublicExponent); bool certIsOK = certificationRequest.Verify(publicKey); // public key is OK here... // get the server certificate Org.BouncyCastle.X509.X509Certificate serverCertificate = DotNetUtilities.FromX509Certificate(System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromCertFile("servermastercertificate.cer")); // get the server private key byte[] privateKeyBytes = File.ReadAllBytes("serverprivate.key"); AsymmetricKeyParameter serverPrivateKey = PrivateKeyFactory.CreateKey(privateKeyBytes); // generate the client certificate X509V3CertificateGenerator generator = new X509V3CertificateGenerator(); generator.SetSerialNumber(BigInteger.ProbablePrime(120, new Random())); generator.SetIssuerDN(serverCertificate.SubjectDN); generator.SetNotBefore(DateTime.Now); generator.SetNotAfter(DateTime.Now.AddYears(5)); generator.SetSubjectDN(certificationRequestInfo.Subject); generator.SetPublicKey(publicKey); generator.SetSignatureAlgorithm("SHA512withRSA"); generator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(serverCertificate)); generator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(publicKey)); var newClientCert = generator.Generate(serverPrivateKey); newClientCert.Verify(publicKey); // <-- this blows up return(DotNetUtilities.ToX509Certificate(newClientCert).Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs12, "user password")); }
public X509Certificate2 CreateMutualAuthenticationX509(string fullSubject, DateTimeOffset validFrom, DateTimeOffset expires) { var random = GetSecureRandom(); // The Certificate Generator var certificateGenerator = new X509V3CertificateGenerator(); certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id, true, new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPClientAuth)); // Serial Number var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random); certificateGenerator.SetSerialNumber(serialNumber); // Issuer and Subject Name var subjectDN = new X509Name(fullSubject); var subjectKeyPair = GenerateRsaKeyPair(); var issuerDN = subjectDN; var issuerKeyPair = subjectKeyPair; certificateGenerator.SetIssuerDN(issuerDN); certificateGenerator.SetSubjectDN(subjectDN); certificateGenerator.SetNotBefore(validFrom.DateTime); certificateGenerator.SetNotAfter(expires.DateTime); certificateGenerator.SetPublicKey(subjectKeyPair.Public); var signatureFactory = new Asn1SignatureFactory(Asn1SignatureAlgorithm, issuerKeyPair.Private, random); var certificate = certificateGenerator.Generate(signatureFactory); var store = new Pkcs12Store(); var friendlyName = certificate.SubjectDN.ToString(); var certificateEntry = new X509CertificateEntry(certificate); var keyEntry = new AsymmetricKeyEntry(subjectKeyPair.Private); store.SetCertificateEntry(friendlyName, certificateEntry); store.SetKeyEntry(friendlyName, keyEntry, new[] { certificateEntry }); var stream = new MemoryStream(); store.Save(stream, new char[0], random); var bytes = stream.ToArray(); return new X509Certificate2(bytes, (string)null, X509KeyStorageFlags.PersistKeySet); }
public static byte[] CreateCertificate(string cn, string password) { if (cn == null) { throw new ArgumentNullException("cn"); } if (password == null) { throw new ArgumentNullException("password"); } RsaKeyPairGenerator rsaKeyPairGenerator = new RsaKeyPairGenerator(); rsaKeyPairGenerator.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 1024)); AsymmetricCipherKeyPair asymmetricCipherKeyPair = rsaKeyPairGenerator.GenerateKeyPair(); BigInteger serialNumber = BigInteger.ProbablePrime(120, new Random()); X509Name x509Name = new X509Name("CN=" + cn); X509V3CertificateGenerator x509V3CertificateGenerator = new X509V3CertificateGenerator(); x509V3CertificateGenerator.SetSerialNumber(serialNumber); x509V3CertificateGenerator.SetSubjectDN(x509Name); x509V3CertificateGenerator.SetIssuerDN(x509Name); x509V3CertificateGenerator.SetNotBefore(DateTime.UtcNow.AddDays(-2.0)); x509V3CertificateGenerator.SetNotAfter(DateTime.UtcNow.AddYears(5)); x509V3CertificateGenerator.SetSignatureAlgorithm("MD5WithRSAEncryption"); x509V3CertificateGenerator.SetPublicKey(asymmetricCipherKeyPair.Public); x509V3CertificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeID[] { KeyPurposeID.IdKPServerAuth, KeyPurposeID.AnyExtendedKeyUsage })); X509Certificate cert = x509V3CertificateGenerator.Generate(asymmetricCipherKeyPair.Private); X509CertificateEntry certEntry = new X509CertificateEntry(cert); Pkcs12Store pkcs12Store = new Pkcs12Store(); pkcs12Store.SetCertificateEntry(cn, certEntry); pkcs12Store.SetKeyEntry(cn, new AsymmetricKeyEntry(asymmetricCipherKeyPair.Private), new X509CertificateEntry[] { new X509CertificateEntry(cert) }); MemoryStream memoryStream = new MemoryStream(); pkcs12Store.Save(memoryStream, password.ToCharArray(), new SecureRandom(new CryptoApiRandomGenerator())); return(memoryStream.ToArray()); }
public static System.Security.Cryptography.X509Certificates.X509Certificate2 CreateSelfSignedCertificate(string hostname) { CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator(); SecureRandom random = new SecureRandom(randomGenerator); X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator(); certGenerator.SetSubjectDN(new X509Name("CN=" + hostname)); certGenerator.SetIssuerDN(new X509Name("CN=" + hostname)); BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random); certGenerator.SetSerialNumber(serialNumber); certGenerator.SetSignatureAlgorithm("SHA256WithRSA"); certGenerator.SetNotBefore(DateTime.UtcNow.Date); certGenerator.SetNotAfter(DateTime.UtcNow.Date.AddYears(10)); KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, 2048); RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); AsymmetricCipherKeyPair keypair = keyPairGenerator.GenerateKeyPair(); certGenerator.SetPublicKey(keypair.Public); var cert = certGenerator.Generate(keypair.Private, random); Pkcs12Store store = new Pkcs12Store(); var certificateEntry = new X509CertificateEntry(cert); store.SetCertificateEntry("cert", certificateEntry); store.SetKeyEntry("cert", new AsymmetricKeyEntry(keypair.Private), new[] { certificateEntry }); var stream = new MemoryStream(); store.Save(stream, "".ToCharArray(), random); return(new X509Certificate2( stream.ToArray(), "", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable)); }
protected static AsymmetricKeyParameter GenerateCA( string subjectName = "CN=Local AjaxLife CA", int strength = 2048, string hashAlgo = "SHA256WithRSA", double age = 86400 ) { CryptoApiRandomGenerator genRandom = new CryptoApiRandomGenerator(); SecureRandom random = new SecureRandom(genRandom); X509V3CertificateGenerator genCert = new X509V3CertificateGenerator(); BigInteger serial = BigIntegers.CreateRandomInRange( BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random ); genCert.SetSerialNumber(serial); genCert.SetSignatureAlgorithm(hashAlgo); X509Name dn = new X509Name(subjectName); genCert.SetSubjectDN(dn); genCert.SetIssuerDN(dn); genCert.SetNotBefore(DateTime.Now.AddSeconds(-86400)); genCert.SetNotAfter(DateTime.Now.AddSeconds(age)); RsaKeyPairGenerator genRsaKeyPair = new RsaKeyPairGenerator(); genRsaKeyPair.Init(new KeyGenerationParameters(random, strength)); AsymmetricCipherKeyPair keypair = genRsaKeyPair.GenerateKeyPair(); genCert.SetPublicKey(keypair.Public); X509Certificate cert = genCert.Generate(keypair.Private, random); X509Certificate2 x509 = new X509Certificate2(cert.GetEncoded()); AddCertToStore(x509, StoreName.Root, StoreLocation.CurrentUser); return(keypair.Private); }
private Org.BouncyCastle.X509.X509Certificate GenerateCertificate( X509Name issuer, X509Name subject, AsymmetricKeyParameter issuerPrivate, AsymmetricKeyParameter subjectPublic) { var signatureFactory = new Asn1SignatureFactory( PkcsObjectIdentifiers.Sha256WithRsaEncryption.ToString(), issuerPrivate); var certGenerator = new X509V3CertificateGenerator(); certGenerator.SetIssuerDN(issuer); certGenerator.SetSubjectDN(subject); certGenerator.SetSerialNumber(BigInteger.ValueOf(1)); certGenerator.SetNotAfter(DateTime.UtcNow.AddHours(1)); certGenerator.SetNotBefore(DateTime.UtcNow); certGenerator.SetPublicKey(subjectPublic); return(certGenerator.Generate(signatureFactory)); }
public static X509Certificate2 GenerateSelfIssuedCertificate(bool isCa) { var keyPair = GenerateKeyPair(publicKeyLength: 2048); var generator = new X509V3CertificateGenerator(); var keyUsages = KeyUsage.DigitalSignature | KeyUsage.KeyCertSign | KeyUsage.CrlSign; if (isCa) { keyUsages |= KeyUsage.KeyCertSign; } generator.AddExtension( X509Extensions.SubjectKeyIdentifier, critical: false, extensionValue: new SubjectKeyIdentifierStructure(keyPair.Public)); generator.AddExtension( X509Extensions.AuthorityKeyIdentifier, critical: false, extensionValue: new AuthorityKeyIdentifierStructure(keyPair.Public)); generator.AddExtension( X509Extensions.BasicConstraints, critical: true, extensionValue: new BasicConstraints(cA: isCa)); generator.AddExtension( X509Extensions.KeyUsage, critical: true, extensionValue: new KeyUsage(keyUsages)); var subjectName = new X509Name($"C=US,ST=WA,L=Redmond,O=NuGet,CN=NuGet Test Self-Issued Certificate ({Guid.NewGuid().ToString()})"); var now = DateTime.UtcNow; generator.SetSerialNumber(BigInteger.One); generator.SetIssuerDN(subjectName); generator.SetNotBefore(now); generator.SetNotAfter(now.AddHours(1)); generator.SetSubjectDN(subjectName); generator.SetPublicKey(keyPair.Public); var signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", keyPair.Private); var certificate = generator.Generate(signatureFactory); return(new X509Certificate2(certificate.GetEncoded())); }
public static X509Certificate2 CreateX509Certificate(Guid ownIdentity, string password) { var keyPairGenerator = new RsaKeyPairGenerator(); var generationParameters = new KeyGenerationParameters( new SecureRandom(new CryptoApiRandomGenerator()), 2048); keyPairGenerator.Init(generationParameters); var keyPair = keyPairGenerator.GenerateKeyPair(); var certificateGenerator = new X509V3CertificateGenerator(); var certificateName = new X509Name("CN=" + ownIdentity.ToString()); var random = new SecureRandom(new CryptoApiRandomGenerator()); var serialNumber = BigInteger.ProbablePrime(120, random); certificateGenerator.SetSerialNumber(serialNumber); certificateGenerator.SetSubjectDN(certificateName); certificateGenerator.SetIssuerDN(certificateName); certificateGenerator.SetNotAfter(DateTime.Now.AddYears(1)); certificateGenerator.SetNotBefore(DateTime.Now); certificateGenerator.SetPublicKey(keyPair.Public); certificateGenerator.AddExtension( X509Extensions.AuthorityKeyIdentifier.Id, false, new AuthorityKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public), new GeneralNames(new GeneralName(certificateName)), serialNumber) ); //certificateGenerator.AddExtension( // X509Extensions.ExtendedKeyUsage.Id, // false, // new ExtendedKeyUsage(KeyPurposeID.AnyExtendedKeyUsage)); var signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", keyPair.Private); var certificate = certificateGenerator.Generate(signatureFactory); return(ToCertificateWithPrivateKey(ownIdentity, certificate, keyPair, password, random)); }
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(); } }
private static Org.BouncyCastle.X509.X509Certificate GenerateCertificate(SecureRandom random, string subjectDN, AsymmetricCipherKeyPair subjectKeyPair, BigInteger subjectSerialNumber, IEnumerable <string> subjectAlternativeNames, string issuerDN, AsymmetricCipherKeyPair issuerKeyPair, int keyUsages, List <KeyPurposeID> extendedKeyUsages, int yearsValid, string signatureAlgorithmName) { var certificateGenerator = new X509V3CertificateGenerator(); certificateGenerator.SetSerialNumber(subjectSerialNumber); var signatureFactory = new Asn1SignatureFactory(signatureAlgorithmName, issuerKeyPair.Private, random); var issuerDN509 = new X509Name(issuerDN); certificateGenerator.SetIssuerDN(issuerDN509); var subjectDN509 = new X509Name(subjectDN); certificateGenerator.SetSubjectDN(subjectDN509); var notBefore = DateTime.UtcNow.Date; var notAfter = notBefore.AddYears(yearsValid); certificateGenerator.SetNotBefore(notBefore); certificateGenerator.SetNotAfter(notAfter); certificateGenerator.SetPublicKey(subjectKeyPair.Public); var subjectKeyIdentifierExtension = new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public)); certificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, false, subjectKeyIdentifierExtension); certificateGenerator.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(false)); // http://tools.ietf.org/html/rfc5280#section-4.2.1.3 if (keyUsages > 0) { certificateGenerator.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(keyUsages)); } certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id, false, new ExtendedKeyUsage(extendedKeyUsages.ToArray())); AddSubjectAlternativeNames(certificateGenerator, subjectAlternativeNames); var certificate = certificateGenerator.Generate(signatureFactory); return(certificate); }
private static X509Certificate GenerateCertificate(X509Name subject, AsymmetricCipherKeyPair keyPair) { X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator(); var now = System.DateTime.Now; var startDate = now.AddDays(-1); var expiryDate = now.AddDays(7); BigInteger serialNumber = BigInteger.ValueOf(new DateTimeOffset(now).ToUnixTimeMilliseconds()); certificateGenerator.SetIssuerDN(subject); certificateGenerator.SetSerialNumber(serialNumber); certificateGenerator.SetNotBefore(startDate); certificateGenerator.SetNotAfter(expiryDate); certificateGenerator.SetSubjectDN(subject); certificateGenerator.SetPublicKey(keyPair.Public); ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256withECDSA", keyPair.Private); return(certificateGenerator.Generate(signatureFactory)); }
public static X509Certificate2 GenerateCeriticate(string subjectName, string Pwd = "bar", string FilePath = "cert.pfx", string Alias = "CryptoModule") { var kpGen = new RsaKeyPairGenerator(); kpGen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), keyLength)); var kp = kpGen.GenerateKeyPair(); var certGenerator = new X509V3CertificateGenerator(); var certName = new X509Name("CN=" + subjectName); var serialNo = BigInteger.ProbablePrime(120, new Random()); certGenerator.SetSerialNumber(serialNo); certGenerator.SetSubjectDN(certName); certGenerator.SetIssuerDN(certName); certGenerator.SetNotAfter(DateTime.Now.AddDays(1)); certGenerator.SetNotBefore(DateTime.Now); certGenerator.SetSignatureAlgorithm("SHA1withRSA"); certGenerator.SetPublicKey(kp.Public); var newCertificate = certGenerator.Generate(kp.Private); var store = new Pkcs12Store(); var certEntry = new X509CertificateEntry(newCertificate); store.SetCertificateEntry(Alias, certEntry); store.SetKeyEntry(Alias, new AsymmetricKeyEntry(kp.Private), new[] { certEntry }); using (var certFile = File.Create(FilePath)) { store.Save(certFile, Pwd.ToCharArray(), new SecureRandom(new CryptoApiRandomGenerator())); } var X509net = new System.Security.Cryptography.X509Certificates.X509Certificate2(FilePath, Pwd, X509KeyStorageFlags.Exportable); ImportCert(X509net); return(X509net); }
internal X509Certificate BuildX509Certificate(TimeSpan certValidity) { var certificateGenerator = new X509V3CertificateGenerator(); certificateGenerator.SetSerialNumber(BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random)); certificateGenerator.SetSubjectDN(subjectDn); certificateGenerator.SetIssuerDN(subjectDn); certificateGenerator.SetNotBefore(DateTime.UtcNow.AddSeconds(-1)); certificateGenerator.SetNotAfter(DateTime.UtcNow.Add(certValidity)); certificateGenerator.SetPublicKey(SubjectKeyPair.Public); var signatureFactory = new Asn1SignatureFactory(signatureAlgorithm, SubjectKeyPair.Private, random); var x509Certificate = certificateGenerator.Generate(signatureFactory); return(x509Certificate); }
// TODO generalize public virtual X509Certificate BuildAuthorizedOCSPResponderCert() { X509Name subjectDnName = new X509Name(subjectDN); BigInteger certSerialNumber = new BigInteger(Convert.ToString(SystemUtil.GetTimeBasedSeed())); // Using the current timestamp as the certificate serial number ISignatureFactory contentSigner = new Asn1SignatureFactory(signatureAlgorithm, (AsymmetricKeyParameter)signingKey); X509V3CertificateGenerator certBuilder = new X509V3CertificateGenerator(); certBuilder.SetIssuerDN(signingCert.SubjectDN); certBuilder.SetSerialNumber(certSerialNumber); certBuilder.SetNotBefore(startDate); certBuilder.SetNotAfter(endDate); certBuilder.SetSubjectDN(subjectDnName); certBuilder.SetPublicKey(publicKey); // TODO generalize extensions setting // Extensions -------------------------- bool ca = true; AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(ca), certBuilder); AddExtension(OcspObjectIdentifiers.PkixOcspNocheck, false, Org.BouncyCastle.Asn1.DerNull.Instance, certBuilder); AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.NonRepudiation), certBuilder); AddExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeID.IdKPOcspSigning), certBuilder); SubjectPublicKeyInfo issuerPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(signingCert.GetPublicKey()); AuthorityKeyIdentifier authKeyIdentifier = new AuthorityKeyIdentifier(issuerPublicKeyInfo); AddExtension(X509Extensions.AuthorityKeyIdentifier, false, authKeyIdentifier, certBuilder); SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey); SubjectKeyIdentifier subjectKeyIdentifier = new SubjectKeyIdentifier(subjectPublicKeyInfo); AddExtension(X509Extensions.SubjectKeyIdentifier, false, subjectKeyIdentifier, certBuilder); // ------------------------------------- return(certBuilder.Generate(contentSigner)); }
private static X509Certificate2 GenerateAndSignCertificate( X509Name subjectName, X509Name issuerName, AsymmetricKeyParameter privateSigningKey) { var randomGenerator = new CryptoApiRandomGenerator(); var random = new SecureRandom(randomGenerator); var certGenerator = new X509V3CertificateGenerator(); var keyGenerationParameters = new KeyGenerationParameters(random, 256); var keyPairGenerator = new ECKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); AsymmetricCipherKeyPair certKeyPair = keyPairGenerator.GenerateKeyPair(); certGenerator.SetPublicKey(certKeyPair.Public); var serialNumber = new BigInteger(64, random); certGenerator.SetSerialNumber(serialNumber); certGenerator.SetSubjectDN(subjectName); certGenerator.SetIssuerDN(issuerName); DateTime notBefore = DateTime.UtcNow - TimeSpan.FromDays(3); DateTime notAfter = DateTime.UtcNow + TimeSpan.FromDays(3); certGenerator.SetNotBefore(notBefore); certGenerator.SetNotAfter(notAfter); certGenerator.AddExtension( X509Extensions.ExtendedKeyUsage, true, ExtendedKeyUsage.GetInstance(new DerSequence(KeyPurposeID.IdKPClientAuth))); ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHECDSA", privateSigningKey, random); var certificate = certGenerator.Generate(signatureFactory); return(new X509Certificate2(DotNetUtilities.ToX509Certificate(certificate))); }
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); }
public void TestCreationRSA() { IBigInteger rsaPubMod = new BigInteger(Base64.Decode("AIASoe2PQb1IP7bTyC9usjHP7FvnUMVpKW49iuFtrw/dMpYlsMMoIU2jupfifDpdFxIktSB4P+6Ymg5WjvHKTIrvQ7SR4zV4jaPTu56Ys0pZ9EDA6gb3HLjtU+8Bb1mfWM+yjKxcPDuFjwEtjGlPHg1Vq+CA9HNcMSKNn2+tW6qt")); IBigInteger rsaPubExp = new BigInteger(Base64.Decode("EQ==")); IBigInteger rsaPrivMod = new BigInteger(Base64.Decode("AIASoe2PQb1IP7bTyC9usjHP7FvnUMVpKW49iuFtrw/dMpYlsMMoIU2jupfifDpdFxIktSB4P+6Ymg5WjvHKTIrvQ7SR4zV4jaPTu56Ys0pZ9EDA6gb3HLjtU+8Bb1mfWM+yjKxcPDuFjwEtjGlPHg1Vq+CA9HNcMSKNn2+tW6qt")); IBigInteger rsaPrivDP = new BigInteger(Base64.Decode("JXzfzG5v+HtLJIZqYMUefJfFLu8DPuJGaLD6lI3cZ0babWZ/oPGoJa5iHpX4Ul/7l3s1PFsuy1GhzCdOdlfRcQ==")); IBigInteger rsaPrivDQ = new BigInteger(Base64.Decode("YNdJhw3cn0gBoVmMIFRZzflPDNthBiWy/dUMSRfJCxoZjSnr1gysZHK01HteV1YYNGcwPdr3j4FbOfri5c6DUQ==")); IBigInteger rsaPrivExp = new BigInteger(Base64.Decode("DxFAOhDajr00rBjqX+7nyZ/9sHWRCCp9WEN5wCsFiWVRPtdB+NeLcou7mWXwf1Y+8xNgmmh//fPV45G2dsyBeZbXeJwB7bzx9NMEAfedchyOwjR8PYdjK3NpTLKtZlEJ6Jkh4QihrXpZMO4fKZWUm9bid3+lmiq43FwW+Hof8/E=")); IBigInteger rsaPrivP = new BigInteger(Base64.Decode("AJ9StyTVW+AL/1s7RBtFwZGFBgd3zctBqzzwKPda6LbtIFDznmwDCqAlIQH9X14X7UPLokCDhuAa76OnDXb1OiE=")); IBigInteger rsaPrivQ = new BigInteger(Base64.Decode("AM3JfD79dNJ5A3beScSzPtWxx/tSLi0QHFtkuhtSizeXdkv5FSba7lVzwEOGKHmW829bRoNxThDy4ds1IihW1w0=")); IBigInteger rsaPrivQinv = new BigInteger(Base64.Decode("Lt0g7wrsNsQxuDdB8q/rH8fSFeBXMGLtCIqfOec1j7FEIuYA/ACiRDgXkHa0WgN7nLXSjHoy630wC5Toq8vvUg==")); RsaKeyParameters rsaPublic = new RsaKeyParameters(false, rsaPubMod, rsaPubExp); RsaPrivateCrtKeyParameters rsaPrivate = new RsaPrivateCrtKeyParameters(rsaPrivMod, rsaPubExp, rsaPrivExp, rsaPrivP, rsaPrivQ, rsaPrivDP, rsaPrivDQ, rsaPrivQinv); 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(); 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("*****@*****.**"); 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(rsaPublic); certGen.SetSignatureAlgorithm("MD5WithRSAEncryption"); X509Certificate cert = certGen.Generate(rsaPrivate); // Assert.IsTrue((cert.IsValidNow && cert.Verify(rsaPublic)),"Certificate failed to be valid (RSA)"); cert.CheckValidity(); cert.Verify(rsaPublic); //Console.WriteLine(ASN1Dump.DumpAsString(cert.ToAsn1Object())); ISet dummySet = cert.GetNonCriticalExtensionOids(); if (dummySet != null) { foreach (string key in dummySet) { Console.WriteLine("\t{0}:\t{1}", key); } } Console.WriteLine(); dummySet = cert.GetNonCriticalExtensionOids(); if (dummySet != null) { foreach (string key in dummySet) { Console.WriteLine("\t{0}:\t{1}", key); } } Console.WriteLine(); }
public void TestCreationECDSA() { IBigInteger ECParraGX = new BigInteger(Base64.Decode("D/qWPNyogWzMM7hkK+35BcPTWFc9Pyf7vTs8uaqv")); IBigInteger ECParraGY = new BigInteger(Base64.Decode("AhQXGxb1olGRv6s1LPRfuatMF+cx3ZTGgzSE/Q5R")); IBigInteger ECParraH = new BigInteger(Base64.Decode("AQ==")); IBigInteger ECParraN = new BigInteger(Base64.Decode("f///////////////f///nl6an12QcfvRUiaIkJ0L")); IBigInteger ECPubQX = new BigInteger(Base64.Decode("HWWi17Yb+Bm3PYr/DMjLOYNFhyOwX1QY7ZvqqM+l")); IBigInteger ECPubQY = new BigInteger(Base64.Decode("JrlJfxu3WGhqwtL/55BOs/wsUeiDFsvXcGhB8DGx")); IBigInteger ECPrivD = new BigInteger(Base64.Decode("GYQmd/NF1B+He1iMkWt3by2Az6Eu07t0ynJ4YCAo")); FPCurve curve = new FPCurve( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECDomainParameters ecDomain = new ECDomainParameters(curve, new FPPoint(curve, curve.FromBigInteger(ECParraGX), curve.FromBigInteger(ECParraGY)), ECParraN); ECPublicKeyParameters ecPub = new ECPublicKeyParameters( "ECDSA", new FPPoint(curve, curve.FromBigInteger(ECPubQX), curve.FromBigInteger(ECPubQY)), ecDomain); ECPrivateKeyParameters ecPriv = new ECPrivateKeyParameters("ECDSA", ECPrivD, ecDomain); 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(); 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("*****@*****.**"); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.SetSerialNumber(BigInteger.One); certGen.SetIssuerDN(new X509Name(ord, attrs)); certGen.SetNotBefore(DateTime.Today.Subtract(new TimeSpan(1, 0, 0, 0))); certGen.SetNotAfter(DateTime.Today.AddDays(1)); certGen.SetSubjectDN(new X509Name(ord, attrs)); certGen.SetPublicKey(ecPub); certGen.SetSignatureAlgorithm("SHA1WITHECDSA"); X509Certificate cert = certGen.Generate(ecPriv); // Assert.IsTrue((cert.IsValidNow && cert.Verify(ecPub)), "Certificate failed to be valid (ECDSA)"); cert.CheckValidity(); cert.Verify(ecPub); ISet dummySet = cert.GetNonCriticalExtensionOids(); if (dummySet != null) { foreach (string key in dummySet) { Console.WriteLine("\t{0}:\t{1}", key); } } Console.WriteLine(); dummySet = cert.GetNonCriticalExtensionOids(); if (dummySet != null) { foreach (string key in dummySet) { Console.WriteLine("\t{0}:\t{1}", key); } } Console.WriteLine(); }
public void TestCreationDSA() { 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(); 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("*****@*****.**"); 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); // Assert.IsTrue((cert.IsValidNow && cert.Verify(dsaPub)), "Certificate failed to be valid (DSA Test)"); cert.CheckValidity(); cert.Verify(dsaPub); ISet dummySet = cert.GetNonCriticalExtensionOids(); if (dummySet != null) { foreach (string key in dummySet) { Console.WriteLine("\t{0}:\t{1}", key); } } Console.WriteLine(); dummySet = cert.GetNonCriticalExtensionOids(); if (dummySet != null) { foreach (string key in dummySet) { Console.WriteLine("\t{0}:\t{1}", key); } } Console.WriteLine(); }