public override string ToString() { StringBuilder buf = new StringBuilder(); string nl = Platform.NewLine; buf.Append(" userCertificate: ").Append(this.SerialNumber).Append(nl); buf.Append(" revocationDate: ").Append(this.RevocationDate).Append(nl); buf.Append(" certificateIssuer: ").Append(this.GetCertificateIssuer()).Append(nl); X509Extensions extensions = c.Extensions; if (extensions != null) { IEnumerator e = extensions.ExtensionOids.GetEnumerator(); if (e.MoveNext()) { buf.Append(" crlEntryExtensions:").Append(nl); do { DerObjectIdentifier oid = (DerObjectIdentifier)e.Current; X509Extension ext = extensions.GetExtension(oid); if (ext.Value != null) { Asn1Object obj = Asn1Object.FromByteArray(ext.Value.GetOctets()); buf.Append(" critical(") .Append(ext.IsCritical) .Append(") "); try { if (oid.Equals(X509Extensions.ReasonCode)) { buf.Append(new CrlReason(DerEnumerated.GetInstance(obj))); } else if (oid.Equals(X509Extensions.CertificateIssuer)) { buf.Append("Certificate issuer: ").Append( GeneralNames.GetInstance((Asn1Sequence)obj)); } else { buf.Append(oid.Id); buf.Append(" value = ").Append(Asn1Dump.DumpAsString(obj)); } buf.Append(nl); } catch (Exception) { buf.Append(oid.Id); buf.Append(" value = ").Append("*****").Append(nl); } } else { buf.Append(nl); } }while (e.MoveNext()); } } return(buf.ToString()); }
/// <summary> /// Gives back the CRL URI meta-data found within the given X509 certificate. /// </summary> /// <returns> /// the CRL URI, or <code>null</code> if the extension is not present. /// </returns> public virtual string GetCrlUri(X509Certificate certificate) { Asn1OctetString crlDistributionPointsValue = certificate.GetExtensionValue(X509Extensions.CrlDistributionPoints); if (null == crlDistributionPointsValue) { return(null); } Asn1Sequence seq; try { DerOctetString oct; //oct = (DEROctetString)(new ASN1InputStream(new ByteArrayInputStream(crlDistributionPointsValue // )).ReadObject()); oct = (DerOctetString)crlDistributionPointsValue; seq = (Asn1Sequence) new Asn1InputStream(oct.GetOctets()).ReadObject(); } catch (IOException e) { throw new Exception("IO error: " + e.Message, e); } CrlDistPoint distPoint = CrlDistPoint.GetInstance(seq); DistributionPoint[] distributionPoints = distPoint.GetDistributionPoints(); foreach (DistributionPoint distributionPoint in distributionPoints) { DistributionPointName distributionPointName = distributionPoint.DistributionPointName; if (DistributionPointName.FullName != distributionPointName.PointType) { continue; } GeneralNames generalNames = (GeneralNames)distributionPointName.Name; GeneralName[] names = generalNames.GetNames(); foreach (GeneralName name in names) { if (name.TagNo != GeneralName.UniformResourceIdentifier) { logger.Info("not a uniform resource identifier"); continue; } string str = null; if (name.ToAsn1Object() is DerTaggedObject) { DerTaggedObject taggedObject = (DerTaggedObject)name.ToAsn1Object(); DerIA5String derStr = DerIA5String.GetInstance(taggedObject.GetObject()); str = derStr.GetString(); } else { DerIA5String derStr = DerIA5String.GetInstance(name.ToAsn1Object()); str = derStr.GetString(); } if (str != null && (str.StartsWith("http://") || str.StartsWith("https://")) && str.ToUpperInvariant().Contains("CRL")) //jbonilla - El URL del CRL para el BCE está en la tercera posición y solo se puede acceder desde HTTP. { return(str); } else { logger.Info("Supports only http:// and https:// protocol for CRL"); } } } //jbonilla #region BCE if (certificate.SubjectDN.ToString() .Contains("AC BANCO CENTRAL DEL ECUADOR")) { return(IntermediateAcUrl); } #endregion return(null); }
internal static X509Certificate2 Build(string hostname) { if (_cachedCertificates.TryGetValue(hostname, out var cachedCert)) { return(cachedCert); } var random = new SecureRandom(); var keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(new KeyGenerationParameters(random, KeyStrength)); var subjectKeyPair = keyPairGenerator.GenerateKeyPair(); var subjectAltName = new GeneralNames(new[] { new GeneralName(GeneralName.IPAddress, "127.0.0.1"), new GeneralName(GeneralName.DnsName, "localhost"), }); var certificateGenerator = new X509V3CertificateGenerator(); var serialNumber = BigInteger.ProbablePrime(120, random); certificateGenerator.SetSerialNumber(serialNumber); certificateGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certificateGenerator.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyEncipherment)); certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth)); certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false, subjectAltName); certificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public))); certificateGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(_rootCertificateKeyPair.Public))); certificateGenerator.AddExtension(X509Extensions.CertificatePolicies, false, new CertificatePolicies( new PolicyInformation(new DerObjectIdentifier("1.2.410.200004.2"), new DerSequence( new PolicyQualifierInfo("https://github.com/devunt/PassiveX"), new PolicyQualifierInfo(PolicyQualifierID.IdQtUnotice, new UserNotice(null, "PassiveX 가 자동으로 생성한 가짜 인증서입니다.")))))); certificateGenerator.SetIssuerDN(new X509Name(_rootCertificate.Issuer)); certificateGenerator.SetSubjectDN(new X509Name($"CN={hostname}")); var notBefore = DateTime.UtcNow.Date; var notAfter = notBefore.AddYears(1); certificateGenerator.SetNotBefore(notBefore); certificateGenerator.SetNotAfter(notAfter); certificateGenerator.SetPublicKey(subjectKeyPair.Public); var signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", _rootCertificateKeyPair.Private, random); var x509 = certificateGenerator.Generate(signatureFactory); var certificate = new X509Certificate2(x509.GetEncoded()); certificate.PrivateKey = DotNetUtilities.ToRSA((RsaPrivateCrtKeyParameters)subjectKeyPair.Private); _cachedCertificates[hostname] = certificate; return(certificate); }
private void doTestGenerateWithCert() { X509CertificateParser fact = new X509CertificateParser(); X509Certificate iCert = fact.ReadCertificate(signCert); // // a sample key pair. // RsaKeyParameters pubKey = new RsaKeyParameters( false, new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16)); // // set up the keys // // PrivateKey privKey; // PublicKey pubKey; // // KeyFactory kFact = KeyFactory.getInstance("RSA"); // // privKey = kFact.generatePrivate(RSA_PRIVATE_KEY_SPEC); // pubKey = kFact.generatePublic(pubKeySpec); IAsymmetricKeyParameter privKey = RSA_PRIVATE_KEY_SPEC; X509V2AttributeCertificateGenerator gen = new X509V2AttributeCertificateGenerator(); // the actual attributes GeneralName roleName = new GeneralName(GeneralName.Rfc822Name, "DAU123456789"); // roleSyntax OID: 2.5.24.72 X509Attribute attributes = new X509Attribute("2.5.24.72", new DerSequence(roleName)); gen.AddAttribute(attributes); gen.SetHolder(new AttributeCertificateHolder(iCert)); gen.SetIssuer(new AttributeCertificateIssuer(new X509Name("cn=test"))); gen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50)); gen.SetNotAfter(DateTime.UtcNow.AddSeconds(50)); gen.SetSerialNumber(BigInteger.One); gen.SetSignatureAlgorithm("SHA1WithRSAEncryption"); IX509AttributeCertificate aCert = gen.Generate(privKey); aCert.CheckValidity(); aCert.Verify(pubKey); AttributeCertificateHolder holder = aCert.Holder; if (holder.GetEntityNames() != null) { Fail("entity names set when none expected"); } if (!holder.SerialNumber.Equals(iCert.SerialNumber)) { Fail("holder serial number doesn't Match"); } if (!holder.GetIssuer()[0].Equivalent(iCert.IssuerDN)) { Fail("holder issuer doesn't Match"); } if (!holder.Match(iCert)) { Fail("generated holder not matching holder certificate"); } X509Attribute[] attrs = aCert.GetAttributes("2.5.24.72"); if (attrs == null) { Fail("attributes related to 2.5.24.72 not found"); } X509Attribute attr = attrs[0]; if (!attr.Oid.Equals("2.5.24.72")) { Fail("attribute oid mismatch"); } Asn1Encodable[] values = attr.GetValues(); GeneralName role = GeneralNames.GetInstance(values[0]).GetNames()[0]; if (role.TagNo != GeneralName.Rfc822Name) { Fail("wrong general name type found in role"); } if (!((IAsn1String)role.Name).GetString().Equals("DAU123456789")) { Fail("wrong general name value found in role"); } X509Certificate sCert = fact.ReadCertificate(holderCertWithBaseCertificateID); if (holder.Match(sCert)) { Fail("generated holder matching wrong certificate"); } equalityAndHashCodeTest(aCert, aCert.GetEncoded()); }
/// <summary> /// /// </summary> /// <remarks>Based on <see cref="http://www.fkollmann.de/v2/post/Creating-certificates-using-BouncyCastle.aspx"/></remarks> /// <param name="subjectName"></param> /// <returns></returns> public static void GenerateCertificate(string subjectName, long serialNumber, DateTime expireOn, System.Security.Cryptography.X509Certificates.X509Certificate2 issuingCertificate, out string thumbprint, out string pemPrivateKey, out string pemPublicCert, out byte[] publicCert, out byte[] pkcs12Data, out string password) { AsymmetricKeyParameter caPrivateKey; var caCert = ReadCertificateFromX509Certificate2(issuingCertificate, out caPrivateKey); var caAuth = new AuthorityKeyIdentifierStructure(caCert); var authKeyId = new AuthorityKeyIdentifier(caAuth.GetKeyIdentifier()); // --------------------------- // Generating Random Numbers var randomGenerator = new CryptoApiRandomGenerator(); var random = new SecureRandom(randomGenerator); var gen = new X509V3CertificateGenerator(); // var certName = new X509Name("CN=" + subjectName); var list = new Dictionary <string, string>(); AddItems(list, "CN", subjectName); AddItems(list, "O", "JFM Concepts, LLC"); AddItems(list, "OU", "VDP Web"); //var simpleCertName = GetItemString(list); //var certNameLight = new X509Name(simpleCertName); list.Add("L", "Boulder"); list.Add("ST", "Colorado"); list.Add("C", "US"); var subjectFull = GetItemString(list); var certName = new X509Name(subjectFull); BigInteger serialNo; if (serialNumber == 0) { serialNo = BigInteger.ProbablePrime(120, random); } else { serialNo = BigInteger.ValueOf(serialNumber); } gen.SetSerialNumber(serialNo); gen.SetSubjectDN(certName); gen.SetIssuerDN(caCert.IssuerDN); var issuerPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(caCert.GetPublicKey()); var issuerGeneralNames = new GeneralNames(new GeneralName(caCert.IssuerDN)); var issuerSerialNumber = caCert.SerialNumber; var authorityKeyIdentifier = new AuthorityKeyIdentifier(issuerPublicKeyInfo, issuerGeneralNames, issuerSerialNumber); gen.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, true, authorityKeyIdentifier); // gen.SetIssuerUniqueID(caCert.IssuerUniqueID.GetBytes()) gen.SetNotAfter(expireOn); gen.SetNotBefore(DateTime.Now.AddHours(-2)); gen.SetSignatureAlgorithm("SHA256WithRSA"); //("MD5WithRSA"); var kpgen = new RsaKeyPairGenerator(); kpgen.Init(new KeyGenerationParameters(random, 2048)); // new SecureRandom(new CryptoApiRandomGenerator()), 2048)); var subjectKeyPair = kpgen.GenerateKeyPair(); gen.SetPublicKey(subjectKeyPair.Public); gen.AddExtension( X509Extensions.ExtendedKeyUsage.Id, false, new ExtendedKeyUsage(new KeyPurposeID[] { KeyPurposeID.IdKPClientAuth, KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPCodeSigning })); //1.3.6.1.5.5.7.3.1 = server authentication //1.3.6.1.5.5.7.3.2 = client authentication //1.3.6.1.5.5.7.3.3 = code signing var certificate = gen.Generate(caPrivateKey); PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private); // merge into X509Certificate2 var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded()); var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded()); if (seq.Count != 9) { throw new PemException("Malformed sequence in RSA private key."); } var rsa = new RsaPrivateKeyStructure(seq); RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); //------------- //RsaPrivateCrtKeyParameters rsaparams = (RsaPrivateCrtKeyParameters)subjectKeyPair.Private; RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(rsaparams); CspParameters cspParameters = new CspParameters(); cspParameters.KeyContainerName = Guid.NewGuid().ToString(); // "MyKeyContainer"; RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(2048, cspParameters); rsaKey.ImportParameters(rsaParameters); // ------------ x509.PrivateKey = rsaKey; // DotNetUtilities.ToRSA(rsaparams); // Generating Random Numbers var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-()#$%^&@+=!"; var rnd = new Random(); password = new string( Enumerable.Repeat(chars, 15) .Select(s => s[rnd.Next(s.Length)]) .ToArray()); thumbprint = x509.Thumbprint.ToLower(); publicCert = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert); var privateKeyPem = new StringBuilder(); var privateKeyPemWriter = new PemWriter(new StringWriter(privateKeyPem)); privateKeyPemWriter.WriteObject(certificate); privateKeyPemWriter.WriteObject(subjectKeyPair.Private); privateKeyPemWriter.Writer.Flush(); pemPrivateKey = privateKeyPem.ToString(); var publicKeyPem = new StringBuilder(); var utf8WithoutBom = new System.Text.UTF8Encoding(false); var publicKeyPemWriter = new PemWriter(new StringWriterWithEncoding(publicKeyPem, utf8WithoutBom)); publicKeyPemWriter.WriteObject(certificate); publicKeyPemWriter.Writer.Flush(); pemPublicCert = publicKeyPem.ToString(); pemPublicCert = pemPublicCert.Replace(Environment.NewLine, "\n"); //only use newline and not returns pkcs12Data = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pfx, password); }