/// <inheritdoc /> public override void InjectReferenceValue(X509Certificate2 value) { Certificate = value; Asn1Object exValue = GetExtensionValue(value); if (exValue == null) { if (IsRequired()) { throw new PolicyRequiredException("Extention " + ExtentionIdentifier.Display + " is marked as required by is not present."); } PolicyValue = new PolicyValue <string>(String.Empty); return; } var aki = AuthorityKeyIdentifier.GetInstance(exValue); byte[] keyId = aki.GetKeyIdentifier(); if (keyId == null) { if (IsRequired()) { throw new PolicyRequiredException("Extention " + ExtentionIdentifier.Display + " is marked as required by is not present."); } PolicyValue = new PolicyValue <string>(String.Empty); } PolicyValue = new PolicyValue <string>(PolicyUtils.CreateByteStringRep(keyId)); }
/// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { var hashCode = 41; // Suitable nullity checks etc, of course :) if (AuthorityKeyIdentifier != null) { hashCode = hashCode * 59 + AuthorityKeyIdentifier.GetHashCode(); } if (CertificatePolicies != null) { hashCode = hashCode * 59 + CertificatePolicies.GetHashCode(); } if (CrlDistributionPoints != null) { hashCode = hashCode * 59 + CrlDistributionPoints.GetHashCode(); } if (IssuerAltName != null) { hashCode = hashCode * 59 + IssuerAltName.GetHashCode(); } if (SubjectAltName != null) { hashCode = hashCode * 59 + SubjectAltName.GetHashCode(); } if (VerifyResult != null) { hashCode = hashCode * 59 + VerifyResult.GetHashCode(); } return(hashCode); } }
protected void AddAuthorityKeyIdentifier( X509V3CertificateGenerator certificateGenerator, X509Name issuerDN, AsymmetricCipherKeyPair issuerKeyPair, BigInteger issuerSerialNumber) { // Indica qual a CA que assinou o certificado. Apenas faz sentido para certificados que não sejam CA's // RFC2459, Secção 4.2.1.1. Neste caso foi adoptado IssuerName + SerialNumber // Nota: pode ser um problema no caso de se recriar a CA // Ver: https://www.v13.gr/blog/?p=293 // Add the Authority Key Identifier. According to http://www.alvestrand.no/objectid/2.5.29.35.html, this // identifies the public key to be used to verify the signature on this certificate. // In a certificate chain, this corresponds to the "Subject Key Identifier" on the *issuer* certificate. // The Bouncy Castle documentation, at http://www.bouncycastle.org/wiki/display/JA1/X.509+Public+Key+Certificate+and+Certification+Request+Generation, // shows how to create this from the issuing certificate. Since we're creating a self-signed certificate, we have to do this slightly differently. var authorityKeyIdentifierExtension = new AuthorityKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerKeyPair.Public), new GeneralNames(new GeneralName(issuerDN)), issuerSerialNumber); certificateGenerator.AddExtension( X509Extensions.AuthorityKeyIdentifier.Id, false, authorityKeyIdentifierExtension); }
/// <summary> /// Authority Key Identifier is an optional field. If present, it should be the key identifier of the parent. /// Absence of the field is a warning. If present, bad linkage is an error. /// </summary> /// <returns></returns> internal bool CheckAuthKeyIdentifierLinkage() { bool ok = true; // alias to root for (int j = 0; j < NumCerts - 1; j++) { var signer = Certs[j + 1]; var target = Certs[j]; var akiData = target.GetExtensionValue(X509Extensions.AuthorityKeyIdentifier); if (akiData == null) { Warning($"Certificate does not contain an Authority Key Identifier Extension: {target.SubjectDN.ToString()}"); continue; } if (akiData != null) { var aki = new AuthorityKeyIdentifierStructure(akiData); var signerKeyId = new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(signer.GetPublicKey())); if (!signerKeyId.Equals(aki)) { Error($"Authority Key Identifier does not match signer for certificate with subject: {target.SubjectDN.ToString()}"); ok = false; } } } return(ok); }
// System.dll v2 doesn't have a class to deal with the AuthorityKeyIdentifier extension private static string GetAuthorityKeyIdentifier(BCX509Certificate2 certificate) { //return GetAuthorityKeyIdentifier (certificate.Extensions["2.5.29.35"]); //return GetAuthorityKeyIdentifier (certificate.CertificateStructure.TbsCertificate.Extensions.GetExtension (new Oid ("2.5.29.35")).GetParsedValue () as AuthorityKeyIdentifier); AuthorityKeyIdentifier ski = AuthorityKeyIdentifier.GetInstance(certificate.CertificateStructure.TbsCertificate.Extensions.GetExtension(X509Extensions.AuthorityKeyIdentifier)); return((ski == null) ? String.Empty : Hex.ToHexString(ski.GetKeyIdentifier())); }
private AuthorityKeyIdentifier GetAKI() { if (X509 == null) { throw new HFCACertificateException("Certificate is null"); } Asn1OctetString akiOc = X509.GetExtensionValue(X509Extensions.AuthorityKeyIdentifier); return(AuthorityKeyIdentifier.GetInstance(Asn1Sequence.GetInstance(akiOc.GetOctets()))); }
//TODO change to functors public static X509Certificate CreateX509Certificate2(AsymmetricCipherKeyPair kp, string issuer, DateTime notBefore, DateTime notAfter, KeyType keyUsage, string filename, string password) { var random = new SecureRandom(); var sf = new Asn1SignatureFactory(HashAlg.SHA256withRSA.ToString(), kp.Private, random); var gen = new X509V3CertificateGenerator(); var serial = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random); gen.SetSerialNumber(serial); var subject = new X509Name(issuer); gen.SetIssuerDN(subject); gen.SetSubjectDN(subject); gen.SetNotBefore(notBefore); gen.SetNotAfter(notAfter); gen.SetPublicKey(kp.Public); gen.AddExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(true)); var subjectKeyIdentifier = new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public)); gen.AddExtension(X509Extensions.SubjectKeyIdentifier, false, subjectKeyIdentifier); var authorityKeyIdentifier = new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public), new GeneralNames(new GeneralName(subject)), serial); gen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, authorityKeyIdentifier); ////gen.AddExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeID.IdKPEmailProtection)); switch (keyUsage) { case KeyType.Signature: //signature gen.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(X509KeyUsage.NonRepudiation)); break; case KeyType.Authentication: //authentication gen.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(X509KeyUsage.DigitalSignature)); break; case KeyType.Encryption: //encryption gen.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(X509KeyUsage.KeyEncipherment | X509KeyUsage.KeyAgreement)); break; default: gen.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(X509KeyUsage.KeyEncipherment | X509KeyUsage.DigitalSignature)); break; } var bouncyCert = gen.Generate(sf); bouncyCert.CheckValidity(); bouncyCert.Verify(kp.Public); var store = new Pkcs12Store(); var certificateEntry = new X509CertificateEntry(bouncyCert); store.SetCertificateEntry(bouncyCert.SubjectDN.ToString(), certificateEntry); store.SetKeyEntry(bouncyCert.SubjectDN.ToString(), new AsymmetricKeyEntry(kp.Private), new[] { certificateEntry }); using (var sw = File.Create(filename)) store.Save(sw, password.ToCharArray(), random); return(bouncyCert); }
/// <summary> /// Add the Authority Key Identifier. According to http://www.alvestrand.no/objectid/2.5.29.35.html, this /// identifies the public key to be used to verify the signature on this certificate. /// In a certificate chain, this corresponds to the "Subject Key Identifier" on the *issuer* certificate. /// The Bouncy Castle documentation, at http://www.bouncycastle.org/wiki/display/JA1/X.509+Public+Key+Certificate+and+Certification+Request+Generation, /// shows how to create this from the issuing certificate. Since we're creating a self-signed certificate, we have to do this slightly differently. /// </summary> /// <param name="certificateGenerator"></param> /// <param name="issuerDN"></param> /// <param name="issuerKeyPair"></param> /// <param name="issuerSerialNumber"></param> private static void AddAuthorityKeyIdentifier(X509V3CertificateGenerator certificateGenerator, X509Name issuerDN, AsymmetricCipherKeyPair issuerKeyPair, BigInteger issuerSerialNumber) { var authorityKeyIdentifierExtension = new AuthorityKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerKeyPair.Public), new GeneralNames(new GeneralName(issuerDN)), issuerSerialNumber); certificateGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, false, authorityKeyIdentifierExtension); }
internal static X509Certificate GenerateCertificate(string subjectName, out AsymmetricCipherKeyPair keyPair) { var keyPairGenerator = new RsaKeyPairGenerator(); // certificate strength 2048 bits keyPairGenerator.Init(new KeyGenerationParameters( new SecureRandom(new CryptoApiRandomGenerator()), 2048)); keyPair = keyPairGenerator.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.AddYears(100)); certGenerator.SetNotBefore(DateTime.Now.Subtract(TimeSpan.FromHours(8))); certGenerator.SetPublicKey(keyPair.Public); var key = new AuthorityKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public), new GeneralNames(new GeneralName(certName)), serialNo); certGenerator.AddExtension( X509Extensions.AuthorityKeyIdentifier.Id, false, key); /* * 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 */ certGenerator.AddExtension( X509Extensions.ExtendedKeyUsage.Id, false, new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth)); var signatureFactory = new Asn1SignatureFactory("SHA256withRSA", keyPair.Private); var generatedCertificate = certGenerator.Generate(signatureFactory); return(generatedCertificate); }
public X509Certificate2 CreateCertificate() { X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator(); var subjectDN = new X509Name(String.Format("CN={0}", SubjectName)); var issuerDN = subjectDN; AsymmetricKeyParameter privateKey; AsymmetricKeyParameter publicKey; RsaKeysGenerator(out privateKey, out publicKey); var authorityKeyIdentifier = new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey), new GeneralNames(new GeneralName(issuerDN)), SerialNumber); var subjectKeyIdentifier = new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey)); certificateGenerator.SetIssuerDN(issuerDN); certificateGenerator.SetSubjectDN(subjectDN); certificateGenerator.SetSerialNumber(SerialNumber); certificateGenerator.SetNotBefore(ValidFrom); certificateGenerator.SetNotAfter(ValidTill); certificateGenerator.SetSignatureAlgorithm(SignatureAlgorithm); certificateGenerator.SetPublicKey(publicKey); certificateGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, false, authorityKeyIdentifier); certificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, false, subjectKeyIdentifier); certificateGenerator.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(false)); var certificate = certificateGenerator.Generate(privateKey, Random); PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey); var x509 = new 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); x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams); return(x509); }
/// <summary> /// Returns true if a KeyID matches one in a certificate /// </summary> /// <param name="KeyId">KeyIDvalue to test</param> /// <param name="Certificate">Certificate to test</param> /// <param name="IdType">Authority or Subject KeyID</param> /// <returns> /// True for a key match /// </returns> /// <exception cref="System.ApplicationException">Authority KeyID extension not found in certificate /// or /// Subject KeyID extension not found in certificate</exception> public static bool TestKeyId(byte[] KeyId, X509Certificate Certificate, KeyIdType IdType) { X509Extensions extensions = Certificate.GetExtensions(); X509Extension ext; AuthorityKeyIdentifier akid; SubjectKeyIdentifier skid; switch (IdType) { case KeyIdType.AKID: ext = extensions.GetExtension(X509Extensions.AuthorityKeyIdentifier); if (ext == null) { throw new ApplicationException("Authority KeyID extension not found in certificate"); } else { akid = AuthorityKeyIdentifier.GetInstance(ext); if (KeyId == akid.GetKeyIdentifier()) { return(true); } } break; case KeyIdType.SKID: ext = extensions.GetExtension(X509Extensions.SubjectKeyIdentifier); if (ext == null) { throw new ApplicationException("Subject KeyID extension not found in certificate"); } else { skid = SubjectKeyIdentifier.GetInstance(ext); if (KeyId == skid.GetKeyIdentifier()) { return(true); } } break; } return(false); }
/// <summary> /// Returns true if VerifyCertificateResponse instances are equal /// </summary> /// <param name="other">Instance of VerifyCertificateResponse to be compared</param> /// <returns>Boolean</returns> public bool Equals(VerifyCertificateResponse other) { if (other is null) { return(false); } if (ReferenceEquals(this, other)) { return(true); } return (( AuthorityKeyIdentifier == other.AuthorityKeyIdentifier || AuthorityKeyIdentifier != null && AuthorityKeyIdentifier.Equals(other.AuthorityKeyIdentifier) ) && ( CertificatePolicies == other.CertificatePolicies || CertificatePolicies != null && CertificatePolicies.Equals(other.CertificatePolicies) ) && ( CrlDistributionPoints == other.CrlDistributionPoints || CrlDistributionPoints != null && CrlDistributionPoints.Equals(other.CrlDistributionPoints) ) && ( IssuerAltName == other.IssuerAltName || IssuerAltName != null && IssuerAltName.Equals(other.IssuerAltName) ) && ( SubjectAltName == other.SubjectAltName || SubjectAltName != null && SubjectAltName.Equals(other.SubjectAltName) ) && ( VerifyResult == other.VerifyResult || VerifyResult != null && VerifyResult.Equals(other.VerifyResult) )); }
// 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 void AddIssuer( this X509V3CertificateGenerator certificateGenerator, string issuerName, AsymmetricCipherKeyPair issuerKeyPair, BigInteger issuerSerialNumber) { var issuerDistributionName = new X509Name(issuerName); certificateGenerator.SetIssuerDN(issuerDistributionName); var authorityKeyIdentifierExtension = new AuthorityKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerKeyPair.Public), new GeneralNames(new GeneralName(issuerDistributionName)), issuerSerialNumber); certificateGenerator.AddExtension( oid: X509Extensions.AuthorityKeyIdentifier.Id, critical: false, extensionValue: authorityKeyIdentifierExtension); }
public static AuthorityKeyIdentifier retrieveAuthorityKeyIdentifier(X509Certificate x509Certificate) { AuthorityKeyIdentifier authorityKeyIdentifier = new AuthorityKeyIdentifier(); X509Extension x509Extension = x509Certificate.CertificateStructure.TbsCertificate.Extensions.GetExtension(new DerObjectIdentifier(OIDS.OID_AUTHORITY_KEY_IDENTIFIER_EXTENSION)); if (x509Extension != null) { Org.BouncyCastle.Asn1.X509.AuthorityKeyIdentifier authorityKeyIdentifierExtension = Org.BouncyCastle.Asn1.X509.AuthorityKeyIdentifier.GetInstance(x509Extension); authorityKeyIdentifier.HasAuthorityKeyIdentifier = true; authorityKeyIdentifier.IsCritical = x509Extension.IsCritical; authorityKeyIdentifier.keyIdentifier = authorityKeyIdentifierExtension.GetKeyIdentifier(); //todo: add issuer and serial fields. } else { authorityKeyIdentifier.HasAuthorityKeyIdentifier = false; } return(authorityKeyIdentifier); }
public static X509Certificate2 CreateX509Certificate2(AsymmetricCipherKeyPair kp) { var random = new SecureRandom(); var sf = new Asn1SignatureFactory(HashAlg.SHA256withRSA.ToString(), kp.Private, random); var gen = new X509V3CertificateGenerator(); gen.SetSerialNumber(BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random)); var subject = new X509Name("CN=" + "ebics.org"); gen.SetSubjectDN(subject); gen.SetIssuerDN(subject); var notBefore = DateTime.UtcNow.Date; var notAfter = notBefore.AddYears(10); gen.SetNotBefore(notBefore); gen.SetNotAfter(notAfter); gen.SetPublicKey(kp.Public); var bouncyCert = gen.Generate(sf); var authorityKeyIdentifier = new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public), new GeneralNames(new GeneralName(subject)), bouncyCert.SerialNumber); gen.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, false, authorityKeyIdentifier); var subjectKeyIdentifier = new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public)); gen.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, false, subjectKeyIdentifier); gen.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(false)); var store = new Pkcs12Store(); var certificateEntry = new X509CertificateEntry(bouncyCert); store.SetCertificateEntry(bouncyCert.SubjectDN.ToString(), certificateEntry); store.SetKeyEntry(bouncyCert.SubjectDN.ToString(), new AsymmetricKeyEntry(kp.Private), new[] { certificateEntry }); const string pwd = "password"; var stream = new MemoryStream(); store.Save(stream, pwd.ToCharArray(), random); var msCert = new X509Certificate2(stream.ToArray(), pwd, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); return(msCert); }
/// <inheritdoc/> public string ToDelimitedString() { CultureInfo culture = CultureInfo.CurrentCulture; return(string.Format( culture, StringHelper.StringFormatSequence(0, 32, Configuration.FieldSeparator), Id, SetIdCer.HasValue ? SetIdCer.Value.ToString(culture) : null, SerialNumber, Version, GrantingAuthority?.ToDelimitedString(), IssuingAuthority?.ToDelimitedString(), Signature?.ToDelimitedString(), GrantingCountry, GrantingStateProvince?.ToDelimitedString(), GrantingCountyParish?.ToDelimitedString(), CertificateType?.ToDelimitedString(), CertificateDomain?.ToDelimitedString(), SubjectId?.ToDelimitedString(), SubjectName, SubjectDirectoryAttributeExtension != null ? string.Join(Configuration.FieldRepeatSeparator, SubjectDirectoryAttributeExtension.Select(x => x.ToDelimitedString())) : null, SubjectPublicKeyInfo?.ToDelimitedString(), AuthorityKeyIdentifier?.ToDelimitedString(), BasicConstraint, CrlDistributionPoint != null ? string.Join(Configuration.FieldRepeatSeparator, CrlDistributionPoint.Select(x => x.ToDelimitedString())) : null, JurisdictionCountry, JurisdictionStateProvince?.ToDelimitedString(), JurisdictionCountyParish?.ToDelimitedString(), JurisdictionBreadth != null ? string.Join(Configuration.FieldRepeatSeparator, JurisdictionBreadth.Select(x => x.ToDelimitedString())) : null, GrantingDate.HasValue ? GrantingDate.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null, IssuingDate.HasValue ? IssuingDate.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null, ActivationDate.HasValue ? ActivationDate.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null, InactivationDate.HasValue ? InactivationDate.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null, ExpirationDate.HasValue ? ExpirationDate.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null, RenewalDate.HasValue ? RenewalDate.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null, RevocationDate.HasValue ? RevocationDate.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null, RevocationReasonCode?.ToDelimitedString(), CertificateStatusCode?.ToDelimitedString() ).TrimEnd(Configuration.FieldSeparator.ToCharArray())); }
private static string GetAuthorityKeyIdentifier(X509Extension ext) { if (ext == null) { return(String.Empty); } AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(ext); byte[] id = aki.Identifier; if (id == null) { return(String.Empty); } StringBuilder sb = new StringBuilder(); foreach (byte b in id) { sb.Append(b.ToString("X02")); } return(sb.ToString()); }
private CertificateUrlTemplateBindModel BuildUrlTemplateBindModel( string name, string subject, string issuer, SubjectKeyIdentifier keyId, AuthorityKeyIdentifier issuerId, BigInteger serialNumber, DateTime notBefore, DateTime notAfter) { string idSubject = Hex.ToHexString(new BigInteger(keyId.GetKeyIdentifier()).ToByteArray()); string idIssuer = Hex.ToHexString(new BigInteger(issuerId.GetKeyIdentifier()).ToByteArray()); return(new CertificateUrlTemplateBindModel( name, subject, issuer, idSubject, idIssuer, serialNumber.ToString(), notBefore, notAfter)); }
/// <summary> /// Create a new certificate /// </summary> /// <param name="issuer">Issuer certificate, if null then self-sign</param> /// <param name="subjectName">Subject name</param> /// <param name="serialNumber">Serial number of certificate, if null then will generate a new one</param> /// <param name="signature">If true create an AT_SIGNATURE key, otherwise AT_EXCHANGE</param> /// <param name="keySize">Size of RSA key</param> /// <param name="notBefore">Start date of certificate</param> /// <param name="notAfter">End date of certificate</param> /// <param name="extensions">Array of extensions, if null then no extensions</param> /// <param name="hashAlgorithm">Specify the signature hash algorithm</param> /// <returns>The created X509 certificate</returns> public SystemX509.X509Certificate2 CreateCert(SystemX509.X509Certificate2 issuer, SystemX509.X500DistinguishedName subjectName, byte[] serialNumber, bool signature, int keySize, CertificateHashAlgorithm hashAlgorithm, DateTime notBefore, DateTime notAfter, SystemX509.X509ExtensionCollection extensions) { X509V3CertificateGenerator builder = new X509V3CertificateGenerator(); AsymmetricAlgorithm subjectKey = CreateRSAKey(keySize, signature); AsymmetricAlgorithm signKey = issuer == null ? subjectKey : issuer.PrivateKey; if (signKey == null) { throw new ArgumentException(Properties.Resources.CreateCert_NoPrivateKey); } AsymmetricCipherKeyPair bcSubjectKey = GetRsaKeyPair((RSACryptoServiceProvider)subjectKey); AsymmetricCipherKeyPair bcSignKey = GetRsaKeyPair((RSACryptoServiceProvider)signKey); X509Name issuerNameObj = issuer == null?X509Name.GetInstance(Asn1Object.FromByteArray(subjectName.RawData)) : X509Name.GetInstance(Asn1Object.FromByteArray(issuer.SubjectName.RawData)); X509Name subjectNameObj = X509Name.GetInstance(Asn1Object.FromByteArray(subjectName.RawData)); BigInteger subjectSerial = new BigInteger(1, serialNumber != null ? serialNumber : Guid.NewGuid().ToByteArray()); BigInteger issuerSerial = issuer == null ? subjectSerial : new BigInteger(1, issuer.GetSerialNumber()); builder.SetIssuerDN(issuerNameObj); builder.SetSubjectDN(subjectNameObj); builder.SetSerialNumber(subjectSerial); builder.SetSignatureAlgorithm(HashAlgorithmToName(hashAlgorithm)); builder.SetNotBefore(notBefore.ToUniversalTime()); builder.SetNotAfter(notAfter.ToUniversalTime()); builder.SetPublicKey(bcSubjectKey.Public); SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(bcSignKey.Public); AuthorityKeyIdentifier authKeyId = new AuthorityKeyIdentifier(info, new GeneralNames(new GeneralName(issuerNameObj)), issuerSerial); SubjectKeyIdentifier subjectKeyid = new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(bcSubjectKey.Public)); builder.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, true, authKeyId); builder.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, true, subjectKeyid); if (extensions != null) { foreach (SystemX509.X509Extension ext in extensions) { if (!ext.Oid.Value.Equals(X509Extensions.AuthorityKeyIdentifier.Id) && !ext.Oid.Value.Equals(X509Extensions.SubjectKeyIdentifier.Id) && !ext.Oid.Value.Equals(szOID_AUTHORITY_KEY_IDENTIFIER2)) { Asn1InputStream istm = new Org.BouncyCastle.Asn1.Asn1InputStream(ext.RawData); Asn1Object obj = istm.ReadObject(); builder.AddExtension(ext.Oid.Value, ext.Critical, obj); } } } X509Certificate cert = builder.Generate(bcSignKey.Private); SystemX509.X509Certificate2 ret = new SystemX509.X509Certificate2(cert.GetEncoded(), (string)null, SystemX509.X509KeyStorageFlags.Exportable); ret.PrivateKey = subjectKey; return(ret); }
///// <summary> ///// Create a new certificate ///// </summary> ///// <param name="issuer">Issuer certificate, if null then self-sign</param> ///// <param name="subjectName">Subject name</param> ///// <param name="serialNumber">Serial number of certificate, if null then will generate a new one</param> ///// <param name="keySize">Size of RSA key</param> ///// <param name="notBefore">Start date of certificate</param> ///// <param name="notAfter">End date of certificate</param> ///// <param name="extensions">Array of extensions, if null then no extensions</param> ///// <param name="hashAlgorithm">Specify the signature hash algorithm</param> ///// <returns>The created X509 certificate</returns> public static SystemX509.X509Certificate2 CreateCert(SystemX509.X509Certificate2 issuer, SystemX509.X500DistinguishedName subjectName, byte[] serialNumber, int keySize, CertificateHashAlgorithm hashAlgorithm, DateTime notBefore, DateTime notAfter, SystemX509.X509ExtensionCollection extensions) { SecureRandom random = new SecureRandom(); X509V3CertificateGenerator builder = new X509V3CertificateGenerator(); AsymmetricCipherKeyPair bcSubjectKey = CreateRSAKey(keySize, random); AsymmetricCipherKeyPair bcSignKey = issuer == null ? bcSubjectKey : issuer.GetBCPrivateKey(); if (bcSignKey == null) { throw new ArgumentException("issuer"); } X509Name issuerNameObj = issuer == null?X509Name.GetInstance(Asn1Object.FromByteArray(subjectName.RawData)) : X509Name.GetInstance(Asn1Object.FromByteArray(issuer.SubjectName.RawData)); X509Name subjectNameObj = X509Name.GetInstance(Asn1Object.FromByteArray(subjectName.RawData)); BigInteger subjectSerial = new BigInteger(1, serialNumber != null ? serialNumber : Guid.NewGuid().ToByteArray()); BigInteger issuerSerial = issuer == null ? subjectSerial : new BigInteger(1, issuer.GetSerialNumber()); builder.SetIssuerDN(issuerNameObj); builder.SetSubjectDN(subjectNameObj); builder.SetSerialNumber(subjectSerial); builder.SetNotBefore(notBefore.ToUniversalTime()); builder.SetNotAfter(notAfter.ToUniversalTime()); builder.SetPublicKey(bcSubjectKey.Public); SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(bcSignKey.Public); AuthorityKeyIdentifier authKeyId = new AuthorityKeyIdentifier(info, new GeneralNames(new GeneralName(issuerNameObj)), issuerSerial); SubjectKeyIdentifier subjectKeyid = new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(bcSubjectKey.Public)); builder.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, true, authKeyId); builder.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, true, subjectKeyid); if (extensions != null) { foreach (SystemX509.X509Extension ext in extensions) { if (!ext.Oid.Value.Equals(X509Extensions.AuthorityKeyIdentifier.Id) && !ext.Oid.Value.Equals(X509Extensions.SubjectKeyIdentifier.Id) && !ext.Oid.Value.Equals(szOID_AUTHORITY_KEY_IDENTIFIER2)) { Asn1InputStream istm = new Asn1InputStream(ext.RawData); Asn1Object obj = istm.ReadObject(); builder.AddExtension(ext.Oid.Value, ext.Critical, obj); } } } X509Certificate cert = builder.Generate(CreateSignatureFactory(hashAlgorithm, bcSignKey, random)); Pkcs12StoreBuilder pkcs = new Pkcs12StoreBuilder(); Pkcs12Store store = pkcs.Build(); X509CertificateEntry entry = new X509CertificateEntry(cert); store.SetCertificateEntry("main", entry); AsymmetricKeyEntry key_entry = new AsymmetricKeyEntry(bcSubjectKey.Private); store.SetKeyEntry("main", key_entry, new[] { entry }); MemoryStream stm = new MemoryStream(); store.Save(stm, new char[0], new SecureRandom()); return(new SystemX509.X509Certificate2(stm.ToArray(), String.Empty, SystemX509.X509KeyStorageFlags.Exportable)); }
public static X509Certificate2 IssueCertificate( string basename, string password, DistinguishedName dn, CertificateType certtype, DateTime notBefore, DateTime notAfter) { var certificateGenerator = new X509V3CertificateGenerator(); var privateOutputPath = ""; var publicOutputPath = ""; /* Prepare output directories */ if (certtype == CertificateType.AuthorityCertificate) { privateOutputPath = AuthorityPrivateCertificatesPath; publicOutputPath = AuthorityPublicCertificatesPath; } else if (certtype == CertificateType.ServerCertificate) { privateOutputPath = ServerPrivateCertificatesPath; publicOutputPath = ServerPublicCertificatesPath; } else { privateOutputPath = UserPrivateCertificatesPath; publicOutputPath = UserPublicCertificatesPath; } /* Certificate Asymmetric Keys */ CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator(); SecureRandom random = new SecureRandom(randomGenerator); KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, 2048); RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); AsymmetricCipherKeyPair subjectKeyPair = keyPairGenerator.GenerateKeyPair(); certificateGenerator.SetPublicKey(subjectKeyPair.Public); /* Certificate Serial Number */ BigInteger serialNumber = BigIntegers.CreateRandomInRange( BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random); certificateGenerator.SetSerialNumber(serialNumber); /* Certificate Date Constrains */ certificateGenerator.SetNotBefore(notBefore); certificateGenerator.SetNotAfter(notAfter); /* Certificate Issuer and Subject DN */ string issuerName = IssuerDN.ToString(); if (certtype == CertificateType.AuthorityCertificate) { /* A Certification Authority is a self signed certificate */ issuerName = dn.ToString(); } certificateGenerator.SetSubjectDN(new X509Name(dn.ToString())); certificateGenerator.SetIssuerDN(new X509Name(issuerName)); /* Certificate Alternative Names */ if (dn.AlternativeNames != null && dn.AlternativeNames.Any()) { var subjectAlternativeNamesExtension = new DerSequence( dn.AlternativeNames.Select(name => new GeneralName(GeneralName.DnsName, name)) .ToArray <Asn1Encodable> ()); certificateGenerator.AddExtension( X509Extensions.SubjectAlternativeName.Id, false, subjectAlternativeNamesExtension); } /* Certificate Keys Usage */ var keyUsageFlags = KeyUsage.KeyCertSign | KeyUsage.KeyEncipherment | KeyUsage.DataEncipherment | KeyUsage.DigitalSignature; if (certtype == CertificateType.AuthorityCertificate || certtype == CertificateType.ServerCertificate) { keyUsageFlags |= KeyUsage.CrlSign | KeyUsage.NonRepudiation; } certificateGenerator.AddExtension( X509Extensions.KeyUsage.Id, false, new KeyUsage(keyUsageFlags)); /* Certificate Extended Key Usages */ if (certtype != CertificateType.AuthorityCertificate) { KeyPurposeID[] extendedUsages = null; if (certtype == CertificateType.ServerCertificate) { extendedUsages = new KeyPurposeID[] { KeyPurposeID.IdKPServerAuth, }; } else { extendedUsages = new KeyPurposeID[] { KeyPurposeID.IdKPClientAuth, KeyPurposeID.IdKPEmailProtection, }; } certificateGenerator.AddExtension( X509Extensions.ExtendedKeyUsage.Id, false, new ExtendedKeyUsage(extendedUsages)); } /* Certificate Authority Key Identifier */ /* A Certification Authority is a self signed certificate */ AsymmetricCipherKeyPair issuerKeyPair = subjectKeyPair;; if (certtype != CertificateType.AuthorityCertificate) { issuerKeyPair = DotNetUtilities.GetKeyPair(IssuerCertificate.PrivateKey); } var issuerPKIFactory = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerKeyPair.Public); var generalNames = new GeneralNames( new GeneralName(new X509Name(issuerName))); /* A Certification Authority is a self signed certificate */ BigInteger issuerSerialNumber = serialNumber; if (certtype != CertificateType.AuthorityCertificate) { issuerSerialNumber = new BigInteger(IssuerCertificate.GetSerialNumber()); } var authorityKIExtension = new AuthorityKeyIdentifier( issuerPKIFactory, generalNames, issuerSerialNumber); certificateGenerator.AddExtension( X509Extensions.AuthorityKeyIdentifier.Id, false, authorityKIExtension); /* Certificate Subject Key Identifier */ var subjectPKIFactory = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public); var subjectKIExtension = new SubjectKeyIdentifier(subjectPKIFactory); certificateGenerator.AddExtension( X509Extensions.SubjectKeyIdentifier.Id, false, subjectKIExtension); /* Certificate Basic constrains */ bool isCertificateAuthority = false; if (certtype == CertificateType.AuthorityCertificate) { isCertificateAuthority = true; } var basicConstrains = new BasicConstraints(isCertificateAuthority); certificateGenerator.AddExtension( X509Extensions.BasicConstraints.Id, true, basicConstrains); /* Generate BouncyCastle Certificate */ ISignatureFactory signatureFactory = new Asn1SignatureFactory( "SHA512WITHRSA", issuerKeyPair.Private, random ); /* Generate P12 Certificate Store and write to disk*/ var store = new Pkcs12Store(); var certificate = certificateGenerator.Generate(signatureFactory); var certificateEntry = new X509CertificateEntry(certificate); var stream = new MemoryStream(); store.SetCertificateEntry(dn.ToString(), certificateEntry); store.SetKeyEntry(dn.ToString(), new AsymmetricKeyEntry(subjectKeyPair.Private), new [] { certificateEntry }); store.Save(stream, password.ToCharArray(), random); File.WriteAllBytes(privateOutputPath + basename + ".p12", stream.ToArray()); /* Convert to Microsoft X509Certificate2 and write to disk pfx and der files */ var convertedCertificate = new X509Certificate2(stream.ToArray(), password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); File.WriteAllBytes(privateOutputPath + basename + ".pfx", convertedCertificate.Export(X509ContentType.Pfx, password)); File.WriteAllBytes(publicOutputPath + basename + ".crt", convertedCertificate.Export(X509ContentType.Cert, password)); return(convertedCertificate); }
public X509CertificateEntry[] GetCertificateChain( string alias) { if (alias == null) { throw new ArgumentNullException("alias"); } if (!IsKeyEntry(alias)) { return(null); } X509CertificateEntry c = GetCertificate(alias); if (c != null) { IList cs = Platform.CreateArrayList(); while (c != null) { X509Certificate x509c = c.Certificate; X509CertificateEntry nextC = null; Asn1OctetString ext = x509c.GetExtensionValue(X509Extensions.AuthorityKeyIdentifier); if (ext != null) { AuthorityKeyIdentifier id = AuthorityKeyIdentifier.GetInstance( Asn1Object.FromByteArray(ext.GetOctets())); if (id.GetKeyIdentifier() != null) { nextC = (X509CertificateEntry)chainCerts[new CertId(id.GetKeyIdentifier())]; } } if (nextC == null) { // // no authority key id, try the Issuer DN // X509Name i = x509c.IssuerDN; X509Name s = x509c.SubjectDN; if (!i.Equivalent(s)) { foreach (CertId certId in chainCerts.Keys) { X509CertificateEntry x509CertEntry = (X509CertificateEntry)chainCerts[certId]; X509Certificate crt = x509CertEntry.Certificate; X509Name sub = crt.SubjectDN; if (sub.Equivalent(i)) { try { x509c.Verify(crt.GetPublicKey()); nextC = x509CertEntry; break; } catch (InvalidKeyException) { // TODO What if it doesn't verify? } } } } } cs.Add(c); if (nextC != c) // self signed - end of the chain { c = nextC; } else { c = null; } } X509CertificateEntry[] result = new X509CertificateEntry[cs.Count]; for (int i = 0; i < cs.Count; ++i) { result[i] = (X509CertificateEntry)cs[i]; } return(result); } return(null); }
public static CertificateStr deserializeCertData(byte[] raw) { int length = raw.Length; int idx = 0; CertificateStr cert = new CertificateStr(); cert.Version = readInt(raw, idx); idx += 4; DeserializationFieldResult serialNumber = readByteArray(raw, idx); cert.SerialNumber = (byte[])serialNumber.value; idx += serialNumber.size; DeserializationFieldResult issuer = deserializeName(raw, idx); cert.issuer = (NameStr)issuer.value; idx += issuer.size; DeserializationFieldResult subject = deserializeName(raw, idx); cert.subject = (NameStr)subject.value; idx += subject.size; Validity validity = new Validity(); validity.NotBefore = readLong(raw, idx); //check idx += 8; validity.NotAfter = readLong(raw, idx); //check idx += 8; cert.Validity = validity; NativeExtendedKeyUsage extendedKeyUsage = new NativeExtendedKeyUsage(); extendedKeyUsage.Count = readInt(raw, idx); idx += 4; DeserializationFieldResult extendedKeyUsageOIDs = readStringArray(raw, idx); extendedKeyUsage.Oids = (CMap <int, string>)extendedKeyUsageOIDs.value; idx += extendedKeyUsageOIDs.size; cert.ExtendedKeyUsage = extendedKeyUsage; NativeKeyUsage keyUsage = new NativeKeyUsage(); keyUsage.Value = readInt(raw, idx); idx += 4; cert.KeyUsage = keyUsage; BasicConstraints basicConstraints = new BasicConstraints(); basicConstraints.HasBasicConstraints = readBool(raw, idx); idx += 1; basicConstraints.IsCa = readBool(raw, idx); idx += 1; basicConstraints.MaxPathLen = readInt(raw, idx); //check FF FF FF FF becomes FF FF FE FE idx += 4; cert.BasicConstraints = basicConstraints; AuthorityKeyIdentifier authorityKeyIdentifier = new AuthorityKeyIdentifier(); DeserializationFieldResult authorityKeyId = readByteArray(raw, idx); authorityKeyIdentifier.keyIdentifier = (byte[])authorityKeyId.value; if (authorityKeyId.size > 2) { authorityKeyIdentifier.HasAuthorityKeyIdentifier = true; } idx += authorityKeyId.size; cert.AuthorityKeyIdentifier = authorityKeyIdentifier; SubjectKeyIdentifier subjectKeyIdentifier = new SubjectKeyIdentifier(); DeserializationFieldResult subjectKeyId = readByteArray(raw, idx); subjectKeyIdentifier.keyIdentifier = (byte[])subjectKeyId.value; if (subjectKeyId.size > 2) { subjectKeyIdentifier.HasSubjectKeyIdentifierExtension = true; } idx += subjectKeyId.size; cert.SubjectKeyIdentifier = subjectKeyIdentifier; DeserializationFieldResult dnsNames = readStringArray(raw, idx); cert.DnsNames = (CMap <int, string>)dnsNames.value; idx += dnsNames.size; DeserializationFieldResult emailAddresses = readStringArray(raw, idx); cert.EmailAddresses = (CMap <int, string>)emailAddresses.value; idx += emailAddresses.size; DeserializationFieldResult ipAddresses = readStringArray(raw, idx); cert.IpAddresses = (CMap <int, string>)ipAddresses.value; idx += ipAddresses.size; DeserializationFieldResult urls = readStringArray(raw, idx); cert.Urls = (CMap <int, string>)urls.value; idx += urls.size; DeserializationFieldResult tbsCertificate = readByteArray(raw, idx); cert.TbsCertificate = (byte[])tbsCertificate.value; idx += tbsCertificate.size; DeserializationFieldResult signatureAlgorithm = readByteArray(raw, idx); cert.SignatureAlgorithm = (byte[])signatureAlgorithm.value; idx += signatureAlgorithm.size; DeserializationFieldResult signatureValue = readByteArray(raw, idx); cert.Signature = (byte[])signatureValue.value; idx += signatureValue.size; DeserializationFieldResult subjectPublicKeyInfo = readByteArray(raw, idx); cert.SubjectPublicKeyInfo = (byte[])subjectPublicKeyInfo.value; idx += subjectPublicKeyInfo.size; DeserializationFieldResult publicKeySignatureAlgorithm = readByteArray(raw, idx); cert.PublicKeyAlgName = (byte[])publicKeySignatureAlgorithm.value; idx += publicKeySignatureAlgorithm.size; DeserializationFieldResult tbsCertificateSignatureAlgorithm = readByteArray(raw, idx); cert.TBSSignatureAlgorithm = (byte[])tbsCertificateSignatureAlgorithm.value; idx += tbsCertificateSignatureAlgorithm.size; // todo return byte[] ? return(cert); }
/// <summary> /// Generate and return a new X509 certificate. /// </summary> /// <returns></returns> public X509Certificate2 Generate() { var generator = new X509V3CertificateGenerator(); // RFC 5280 section 4.1.2.2. Serial Number generator.SetSerialNumber(SerialNumber); // RFC 5280 section 4.1.2.4. Issuer generator.SetIssuerDN(IssuerDN); // RFC 5280 section 4.1.2.5. Validity if (!IsSelfSigned && NotBefore < Issuer.NotBefore) { NotBefore = Issuer.NotBefore; } if (!IsSelfSigned && Issuer.NotAfter < NotAfter) { NotAfter = Issuer.NotAfter; } generator.SetNotBefore(NotBefore); generator.SetNotAfter(NotAfter); // RFC 5280 section 4.1.2.6. Subject; also see Direct Project 1.2 section 4.1.1.2. generator.SetSubjectDN(SubjectDN); // RFC 5280 section 4.1.2.7. Subject Public Key Info generator.SetPublicKey(SubjectKeyPair.Public); // RFC 5280 section 4.2.1.1. Authority Key Identifier if (IsSelfSigned) { var authorityKeyIdentifier = new AuthorityKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(SubjectKeyPair.Public), new GeneralNames(new GeneralName(SubjectDN)), SerialNumber); generator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, authorityKeyIdentifier); } else { generator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(Issuer)); } // RFC 5280 section 4.2.1.2. Subject Key Identifier var subjectKeyIdentifier = new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(SubjectKeyPair.Public)); generator.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, false, subjectKeyIdentifier); // RFC 5280 section 4.2.1.3. Key Usage generator.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage((int)KeyUsage)); // RFC 5280 section 4.2.1.4. Certificate Policies if (Policies.Any()) { var policies = Policies.Select(x => new PolicyInformation(new DerObjectIdentifier(x))).ToArray(); generator.AddExtension(X509Extensions.CertificatePolicies, false, new CertificatePolicies(policies)); } // RFC 5280 section 4.2.1.6. Subject Alternative Name; also see Direct Project 1.2 section 4.1.1.1. generator.AddExtension(X509Extensions.SubjectAlternativeName, false, SubjectAlternativeName); // RFC 5280 section 4.2.1.9. Basic Constraints generator.AddExtension(X509Extensions.BasicConstraints, true, BasicConstraints); // RFC 5280 section 4.2.1.12. Extended Key Usage generator.AddExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeID.IdKPEmailProtection)); // RFC 5280 section 4.2.1.13. CRL Distribution Points var crlDistPoint = GetCrlDistributionPoints(); if (crlDistPoint != null) { generator.AddExtension(X509Extensions.CrlDistributionPoints, false, crlDistPoint); } // RFC 5280 section 4.2.2.1. Authority Information Access var authorityInfoAccess = GetAuthorityInfoAccessEncoded(); if (authorityInfoAccess != null) { generator.AddExtension(X509Extensions.AuthorityInfoAccess, false, authorityInfoAccess); } // Generate a new certificate. var certificate = generator.Generate(new Asn1SignatureFactory(SignatureAlgorithmName, (IssuerKeyPair ?? SubjectKeyPair).Private, SecureRandom)); // Create a PKCS12 store (a.PFX file) in memory, and add the public and private key to that. var store = new Pkcs12Store(); var certificateEntry = new X509CertificateEntry(certificate); string friendlyName = certificate.SubjectDN.ToString(); store.SetCertificateEntry(friendlyName, certificateEntry); store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(SubjectKeyPair.Private), new[] { certificateEntry }); using (var stream = new MemoryStream()) { // The password is required by the API, but will not be used beyond this scope. const string password = "******"; store.Save(stream, password.ToCharArray(), SecureRandom); return(new X509Certificate2( stream.ToArray(), password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable)); } }
// Only the ctor should be calling with isAuthority = true // if isAuthority, value for isMachineCert doesn't matter private X509CertificateContainer CreateCertificate(bool isAuthority, bool isMachineCert, X509Certificate signingCertificate, params string[] subjects) { if (!isAuthority ^ (signingCertificate != null)) { throw new ArgumentException("Either isAuthority == true or signingCertificate is not null"); } if (!isAuthority && (subjects == null || subjects.Length == 0)) { throw new ArgumentException("If not creating an authority, must specify at least one Subject", "subjects"); } if (!isAuthority && string.IsNullOrWhiteSpace(subjects[0])) { throw new ArgumentException("Certificate Subject must not be an empty string or only whitespace", "subjects"); } EnsureInitialized(); _certGenerator.Reset(); _certGenerator.SetSignatureAlgorithm(_signatureAlthorithm); X509Name authorityX509Name = CreateX509Name(_authorityCanonicalName); var keyPair = isAuthority ? _authorityKeyPair : _keyPairGenerator.GenerateKeyPair(); if (isAuthority) { _certGenerator.SetIssuerDN(authorityX509Name); _certGenerator.SetSubjectDN(authorityX509Name); var authorityKeyIdentifier = new AuthorityKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(_authorityKeyPair.Public), new GeneralNames(new GeneralName(authorityX509Name)), new BigInteger(7, _random).Abs()); _certGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, true, authorityKeyIdentifier); _certGenerator.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(X509KeyUsage.DigitalSignature | X509KeyUsage.KeyAgreement | X509KeyUsage.KeyCertSign | X509KeyUsage.KeyEncipherment | X509KeyUsage.CrlSign)); } else { X509Name subjectName = CreateX509Name(subjects[0]); _certGenerator.SetIssuerDN(PrincipalUtilities.GetSubjectX509Principal(signingCertificate)); _certGenerator.SetSubjectDN(subjectName); _certGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, true, new AuthorityKeyIdentifierStructure(_authorityKeyPair.Public)); _certGenerator.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(X509KeyUsage.DigitalSignature | X509KeyUsage.KeyAgreement | X509KeyUsage.KeyEncipherment)); } _certGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.Public)); _certGenerator.SetSerialNumber(new BigInteger(64 /*sizeInBits*/, _random).Abs()); _certGenerator.SetNotBefore(_validityNotBefore); _certGenerator.SetNotAfter(_validityNotAfter); _certGenerator.SetPublicKey(keyPair.Public); _certGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(isAuthority)); _certGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPClientAuth)); if (!isAuthority) { if (isMachineCert) { List <Asn1Encodable> subjectAlternativeNames = new List <Asn1Encodable>(); // All endpoints should also be in the Subject Alt Names for (int i = 0; i < subjects.Length; i++) { if (!string.IsNullOrWhiteSpace(subjects[i])) { // Machine certs can have additional DNS names subjectAlternativeNames.Add(new GeneralName(GeneralName.DnsName, subjects[i])); } } _certGenerator.AddExtension(X509Extensions.SubjectAlternativeName, true, new DerSequence(subjectAlternativeNames.ToArray())); } else { if (subjects.Length > 1) { var subjectAlternativeNames = new Asn1EncodableVector(); // Only add a SAN for the user if there are any for (int i = 1; i < subjects.Length; i++) { if (!string.IsNullOrWhiteSpace(subjects[i])) { Asn1EncodableVector otherNames = new Asn1EncodableVector(); otherNames.Add(new DerObjectIdentifier(_upnObjectId)); otherNames.Add(new DerTaggedObject(true, 0, new DerUtf8String(subjects[i]))); Asn1Object genName = new DerTaggedObject(false, 0, new DerSequence(otherNames)); subjectAlternativeNames.Add(genName); } } _certGenerator.AddExtension(X509Extensions.SubjectAlternativeName, true, new DerSequence(subjectAlternativeNames)); } } } var crlDistributionPoints = new DistributionPoint[1] { new DistributionPoint(new DistributionPointName( new GeneralNames(new GeneralName(GeneralName.UniformResourceIdentifier, _crlUri))), null, new GeneralNames(new GeneralName(authorityX509Name))) }; var revocationListExtension = new CrlDistPoint(crlDistributionPoints); _certGenerator.AddExtension(X509Extensions.CrlDistributionPoints, false, revocationListExtension); X509Certificate cert = _certGenerator.Generate(_authorityKeyPair.Private, _random); EnsureCertificateValidity(cert); // For now, given that we don't know what format to return it in, preserve the formats so we have // the flexibility to do what we need to X509CertificateContainer container = new X509CertificateContainer(); X509CertificateEntry[] chain = new X509CertificateEntry[1]; chain[0] = new X509CertificateEntry(cert); Pkcs12Store store = new Pkcs12StoreBuilder().Build(); store.SetKeyEntry("", new AsymmetricKeyEntry(keyPair.Private), chain); using (MemoryStream stream = new MemoryStream()) { store.Save(stream, _password.ToCharArray(), _random); container.Pfx = stream.ToArray(); } X509Certificate2 outputCert; if (isAuthority) { // don't hand out the private key for the cert when it's the authority outputCert = new X509Certificate2(cert.GetEncoded()); } else { // Otherwise, allow encode with the private key. note that X509Certificate2.RawData will not provide the private key // you will have to re-export this cert if needed outputCert = new X509Certificate2(container.Pfx, _password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); } container.Subject = subjects[0]; container.InternalCertificate = cert; container.Certificate = outputCert; container.Thumbprint = outputCert.Thumbprint; Trace.WriteLine("[CertificateGenerator] generated a certificate:"); Trace.WriteLine(string.Format(" {0} = {1}", "isAuthority", isAuthority)); if (!isAuthority) { Trace.WriteLine(string.Format(" {0} = {1}", "Signed by", signingCertificate.SubjectDN)); Trace.WriteLine(string.Format(" {0} = {1}", "Subject (CN) ", subjects[0])); Trace.WriteLine(string.Format(" {0} = {1}", "Alt names ", string.Join(", ", subjects))); } Trace.WriteLine(string.Format(" {0} = {1}", "HasPrivateKey:", outputCert.HasPrivateKey)); Trace.WriteLine(string.Format(" {0} = {1}", "Thumbprint", outputCert.Thumbprint)); return(container); }
// Only the ctor should be calling with isAuthority = true // if isAuthority, value for isMachineCert doesn't matter private X509CertificateContainer CreateCertificate(bool isAuthority, bool isMachineCert, X509Certificate signingCertificate, CertificateCreationSettings certificateCreationSettings) { if (certificateCreationSettings == null) { if (isAuthority) { certificateCreationSettings = new CertificateCreationSettings(); } else { throw new Exception("Parameter certificateCreationSettings cannot be null when isAuthority is false"); } } // Set to default cert creation settings if not set if (certificateCreationSettings.ValidityNotBefore == default(DateTime)) { certificateCreationSettings.ValidityNotBefore = _defaultValidityNotBefore; } if (certificateCreationSettings.ValidityNotAfter == default(DateTime)) { certificateCreationSettings.ValidityNotAfter = _defaultValidityNotAfter; } if (!isAuthority ^ (signingCertificate != null)) { throw new ArgumentException("Either isAuthority == true or signingCertificate is not null"); } string subject = certificateCreationSettings.Subject; // If certificateCreationSettings.SubjectAlternativeNames == null, then we should add exactly one SubjectAlternativeName == Subject // so that the default certificate generated is compatible with mainline scenarios // However, if certificateCreationSettings.SubjectAlternativeNames == string[0], then allow this as this is a legit scenario we want to test out if (certificateCreationSettings.SubjectAlternativeNames == null) { certificateCreationSettings.SubjectAlternativeNames = new string[1] { subject }; } string[] subjectAlternativeNames = certificateCreationSettings.SubjectAlternativeNames; if (!isAuthority && string.IsNullOrWhiteSpace(subject)) { throw new ArgumentException("Certificate Subject must not be an empty string or only whitespace", "creationSettings.Subject"); } EnsureInitialized(); s_certGenerator.Reset(); s_certGenerator.SetSignatureAlgorithm(_signatureAlthorithm); // Tag on the generation time to prevent caching of the cert CRL in Linux X509Name authorityX509Name = CreateX509Name(string.Format("{0} {1}", _authorityCanonicalName, DateTime.Now.ToString("s"))); var serialNum = new BigInteger(64 /*sizeInBits*/, _random).Abs(); var keyPair = isAuthority ? _authorityKeyPair : _keyPairGenerator.GenerateKeyPair(); if (isAuthority) { s_certGenerator.SetIssuerDN(authorityX509Name); s_certGenerator.SetSubjectDN(authorityX509Name); var authorityKeyIdentifier = new AuthorityKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(_authorityKeyPair.Public), new GeneralNames(new GeneralName(authorityX509Name)), serialNum); s_certGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, authorityKeyIdentifier); s_certGenerator.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(X509KeyUsage.DigitalSignature | X509KeyUsage.KeyAgreement | X509KeyUsage.KeyCertSign | X509KeyUsage.KeyEncipherment | X509KeyUsage.CrlSign)); } else { X509Name subjectName = CreateX509Name(subject); s_certGenerator.SetIssuerDN(PrincipalUtilities.GetSubjectX509Principal(signingCertificate)); s_certGenerator.SetSubjectDN(subjectName); s_certGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(_authorityKeyPair.Public)); s_certGenerator.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(X509KeyUsage.DigitalSignature | X509KeyUsage.KeyAgreement | X509KeyUsage.KeyEncipherment)); } s_certGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.Public)); s_certGenerator.SetSerialNumber(serialNum); s_certGenerator.SetNotBefore(certificateCreationSettings.ValidityNotBefore); s_certGenerator.SetNotAfter(certificateCreationSettings.ValidityNotAfter); s_certGenerator.SetPublicKey(keyPair.Public); s_certGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(isAuthority)); s_certGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPClientAuth)); if (!isAuthority) { if (isMachineCert) { List <Asn1Encodable> subjectAlternativeNamesAsAsn1EncodableList = new List <Asn1Encodable>(); // All endpoints should also be in the Subject Alt Names for (int i = 0; i < subjectAlternativeNames.Length; i++) { if (!string.IsNullOrWhiteSpace(subjectAlternativeNames[i])) { // Machine certs can have additional DNS names subjectAlternativeNamesAsAsn1EncodableList.Add(new GeneralName(GeneralName.DnsName, subjectAlternativeNames[i])); } } s_certGenerator.AddExtension(X509Extensions.SubjectAlternativeName, true, new DerSequence(subjectAlternativeNamesAsAsn1EncodableList.ToArray())); } else { if (subjectAlternativeNames.Length > 1) { var subjectAlternativeNamesAsAsn1EncodableList = new Asn1EncodableVector(); // Only add a SAN for the user if there are any for (int i = 1; i < subjectAlternativeNames.Length; i++) { if (!string.IsNullOrWhiteSpace(subjectAlternativeNames[i])) { Asn1EncodableVector otherNames = new Asn1EncodableVector(); otherNames.Add(new DerObjectIdentifier(_upnObjectId)); otherNames.Add(new DerTaggedObject(true, 0, new DerUtf8String(subjectAlternativeNames[i]))); Asn1Object genName = new DerTaggedObject(false, 0, new DerSequence(otherNames)); subjectAlternativeNamesAsAsn1EncodableList.Add(genName); } } s_certGenerator.AddExtension(X509Extensions.SubjectAlternativeName, true, new DerSequence(subjectAlternativeNamesAsAsn1EncodableList)); } } } if (isAuthority || certificateCreationSettings.IncludeCrlDistributionPoint) { var crlDistributionPoints = new DistributionPoint[1] { new DistributionPoint( new DistributionPointName( new GeneralNames( new GeneralName( GeneralName.UniformResourceIdentifier, string.Format("{0}", _crlUri, serialNum.ToString(radix: 16))))), null, null) }; var revocationListExtension = new CrlDistPoint(crlDistributionPoints); s_certGenerator.AddExtension(X509Extensions.CrlDistributionPoints, false, revocationListExtension); } X509Certificate cert = s_certGenerator.Generate(_authorityKeyPair.Private, _random); switch (certificateCreationSettings.ValidityType) { case CertificateValidityType.Revoked: RevokeCertificateBySerialNumber(serialNum.ToString(radix: 16)); break; case CertificateValidityType.Expired: break; default: EnsureCertificateIsValid(cert); break; } // For now, given that we don't know what format to return it in, preserve the formats so we have // the flexibility to do what we need to X509CertificateContainer container = new X509CertificateContainer(); X509CertificateEntry[] chain = new X509CertificateEntry[1]; chain[0] = new X509CertificateEntry(cert); Pkcs12Store store = new Pkcs12StoreBuilder().Build(); store.SetKeyEntry( certificateCreationSettings.FriendlyName != null ? certificateCreationSettings.FriendlyName : string.Empty, new AsymmetricKeyEntry(keyPair.Private), chain); using (MemoryStream stream = new MemoryStream()) { store.Save(stream, _password.ToCharArray(), _random); container.Pfx = stream.ToArray(); } X509Certificate2 outputCert; if (isAuthority) { // don't hand out the private key for the cert when it's the authority outputCert = new X509Certificate2(cert.GetEncoded()); } else { // Otherwise, allow encode with the private key. note that X509Certificate2.RawData will not provide the private key // you will have to re-export this cert if needed outputCert = new X509Certificate2(container.Pfx, _password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); } container.Subject = subject; container.InternalCertificate = cert; container.Certificate = outputCert; container.Thumbprint = outputCert.Thumbprint; Trace.WriteLine("[CertificateGenerator] generated a certificate:"); Trace.WriteLine(string.Format(" {0} = {1}", "isAuthority", isAuthority)); if (!isAuthority) { Trace.WriteLine(string.Format(" {0} = {1}", "Signed by", signingCertificate.SubjectDN)); Trace.WriteLine(string.Format(" {0} = {1}", "Subject (CN) ", subject)); Trace.WriteLine(string.Format(" {0} = {1}", "Subject Alt names ", string.Join(", ", subjectAlternativeNames))); Trace.WriteLine(string.Format(" {0} = {1}", "Friendly Name ", certificateCreationSettings.FriendlyName)); } Trace.WriteLine(string.Format(" {0} = {1}", "HasPrivateKey:", outputCert.HasPrivateKey)); Trace.WriteLine(string.Format(" {0} = {1}", "Thumbprint", outputCert.Thumbprint)); Trace.WriteLine(string.Format(" {0} = {1}", "CertificateValidityType", certificateCreationSettings.ValidityType)); return(container); }
static void Main(string[] args) { foreach (string s in args) { if (s.StartsWith("-out:")) { outputfile = s.Replace("-out:", ""); } if (s.StartsWith("-in:")) { certfile = s.Replace("-in:", ""); } } if (outputfile != "stdout") { str = new StreamWriter(outputfile, false); } System.Security.Cryptography.X509Certificates.X509Certificate2 cer = new System.Security.Cryptography.X509Certificates.X509Certificate2(File.ReadAllBytes(certfile)); Al.Security.X509.X509Certificate CERT = Al.Security.Security.DotNetUtilities.FromX509Certificate(cer); Print("Certificate"); Print(" Data"); Print(" Version : " + cer.Version.ToString()); Print(" Valid : " + cer.Verify().ToString()); Print(" Serial Number:"); Print(" " + cer.SerialNumber); Print(" Signature Algorithm : "); Print(" " + cer.SignatureAlgorithm.FriendlyName); Print(" Issuer : " + cer.Issuer); Print(" Validity : "); Print(" Not Before : " + GetRFC822Date(cer.NotBefore)); Print(" Not After : " + GetRFC822Date(cer.NotAfter)); Print(" Subject : " + cer.Subject); Print(" Subject Public Key Info:"); Print(" Public Key Exchange Algorithm: " + cer.PublicKey.Key.KeyExchangeAlgorithm); Print(" Public Key: " + cer.PublicKey.Key.KeySize.ToString() + " bit"); Print(" Modulus:"); Print(cer.GetPublicKey(), " "); if (CERT.GetPublicKey() is Al.Security.Crypto.Parameters.RsaKeyParameters) { RsaKeyParameters rsa = (RsaKeyParameters)CERT.GetPublicKey(); Print(" Exponent:" + rsa.Exponent); } else if (CERT.GetPublicKey() is Al.Security.Crypto.Parameters.DsaKeyParameters) { DsaKeyParameters dsa = (DsaKeyParameters)CERT.GetPublicKey(); Print(" DSA Parameters:"); Print(" G:"); Print(" " + dsa.Parameters.G.ToString()); Print(" P:"); Print(" " + dsa.Parameters.P.ToString()); Print(" Q:"); Print(" " + dsa.Parameters.Q.ToString()); } // Extensions Print(" X509 Extensions"); string extab = " "; bool critical = true; foreach (string oid in CERT.GetCriticalExtensionOids()) { Print(" "); X509Extension ext = new X509Extension(true, CERT.GetExtensionValue(oid)); if (oid == X509Extensions.BasicConstraints.Id) { BasicConstraints bc = BasicConstraints.GetInstance(ext); Print(extab + "Basic Constraints Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " CA:" + bc.IsCA().ToString()); if (bc.PathLenConstraint != null) { Print(extab + " Path Length:" + bc.PathLenConstraint.ToString()); } else { Print(extab + " Path Length:Null"); } } else if (oid == X509Extensions.KeyUsage.Id) { KeyUsage keyu = KeyUsage.GetInstance(ext); Print(extab + "Key Usage Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Key Usages:" + keyu.ToString()); } else if (oid == X509Extensions.ExtendedKeyUsage.Id) { ExtendedKeyUsage keyu = ExtendedKeyUsage.GetInstance(ext); Print(extab + "Extended Key Usage Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Extended Key Usages:"); foreach (DerObjectIdentifier id in keyu.GetAllUsages()) { Print(extab + " " + id.Id); } } else if (oid == X509Extensions.SubjectKeyIdentifier.Id) { SubjectKeyIdentifier keyu = SubjectKeyIdentifier.GetInstance(ext); Print(extab + "Subject Key Identifier Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Key Identifier:"); Print(keyu.GetKeyIdentifier(), extab + " "); } else if (oid == X509Extensions.AuthorityKeyIdentifier.Id) { AuthorityKeyIdentifier keyu = AuthorityKeyIdentifier.GetInstance(ext); Print(extab + "Authority Key Identifier Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Key Identifier:"); Print(keyu.GetKeyIdentifier(), extab + " "); } else if (oid == X509Extensions.SubjectAlternativeName.Id) { Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(ext.Value); GeneralNames keyu = GeneralNames.GetInstance(asn1Object); Print(extab + "Subject Alternative Name Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " General Names:"); foreach (GeneralName gen in keyu.GetNames()) { string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " " + tagname + " " + gen.Name); } } else if (oid == X509Extensions.IssuerAlternativeName.Id) { Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(ext.Value); GeneralNames keyu = GeneralNames.GetInstance(asn1Object); Print(extab + "Issuer Alternative Name Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " General Names:"); foreach (GeneralName gen in keyu.GetNames()) { string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " " + tagname + " " + gen.Name); } } else if (oid == X509Extensions.AuthorityInfoAccess.Id) { AuthorityInformationAccess keyu = AuthorityInformationAccess.GetInstance(ext); Print(extab + "Authority Information Access Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Access Descriptions:"); foreach (AccessDescription acc in keyu.GetAccessDescriptions()) { Print(extab + " Method:" + acc.AccessMethod.Id); GeneralName gen = acc.AccessLocation; string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " Access Location:" + tagname + "=" + gen.Name); } } else if (oid == X509Extensions.SubjectInfoAccess.Id) { AuthorityInformationAccess keyu = AuthorityInformationAccess.GetInstance(ext); Print(extab + "Subject Information Access Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Access Descriptions:"); foreach (AccessDescription acc in keyu.GetAccessDescriptions()) { Print(extab + " Method:" + acc.AccessMethod.Id); GeneralName gen = acc.AccessLocation; string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " Access Location:" + tagname + "=" + gen.Name); } } else if (oid == X509Extensions.CrlDistributionPoints.Id) { Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(ext.Value); CrlDistPoint keyu = CrlDistPoint.GetInstance(asn1Object); Print(extab + "Crl Distribution Points Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Distribution Points:"); foreach (DistributionPoint acc in keyu.GetDistributionPoints()) { if (acc.Reasons != null) { Print(extab + " Reasons:" + acc.Reasons.GetString()); } else { Print(extab + " Reasons:Null"); } if (acc.CrlIssuer != null) { Print(extab + " Crl Issuer:"); foreach (GeneralName gen in acc.CrlIssuer.GetNames()) { string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " " + tagname + ": " + gen.Name); } } else { Print(extab + " Crl Issuer:Null"); } Print(extab + " Distribution Point Name:"); if (acc.DistributionPointName.PointType == DistributionPointName.FullName) { GeneralNames sgen = GeneralNames.GetInstance(acc.DistributionPointName.Name); foreach (GeneralName gen in sgen.GetNames()) { string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " " + tagname + " " + gen.Name); } } else { Print(extab + " Not Supported by OCT"); } } } } critical = false; foreach (string oid in CERT.GetNonCriticalExtensionOids()) { Print(" "); X509Extension ext = new X509Extension(true, CERT.GetExtensionValue(oid)); if (oid == X509Extensions.BasicConstraints.Id) { BasicConstraints bc = BasicConstraints.GetInstance(ext); Print(extab + "Basic Constraints Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " CA:" + bc.IsCA().ToString()); if (bc.PathLenConstraint != null) { Print(extab + " Path Length:" + bc.PathLenConstraint.ToString()); } else { Print(extab + " Path Length:Null"); } } else if (oid == X509Extensions.KeyUsage.Id) { KeyUsage keyu = KeyUsage.GetInstance(ext); Print(extab + "Key Usage Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Key Usages:" + keyu.ToString()); } else if (oid == X509Extensions.ExtendedKeyUsage.Id) { ExtendedKeyUsage keyu = ExtendedKeyUsage.GetInstance(ext); Print(extab + "Extended Key Usage Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Extended Key Usages:"); foreach (DerObjectIdentifier id in keyu.GetAllUsages()) { Print(extab + " " + id.Id); } } else if (oid == X509Extensions.SubjectKeyIdentifier.Id) { SubjectKeyIdentifier keyu = SubjectKeyIdentifier.GetInstance(ext); Print(extab + "Subject Key Identifier Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Key Identifier:"); Print(keyu.GetKeyIdentifier(), extab + " "); } else if (oid == X509Extensions.AuthorityKeyIdentifier.Id) { AuthorityKeyIdentifier keyu = AuthorityKeyIdentifier.GetInstance(ext); Print(extab + "Authority Key Identifier Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Key Identifier:"); Print(keyu.GetKeyIdentifier(), extab + " "); } else if (oid == X509Extensions.SubjectAlternativeName.Id) { Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(ext.Value); GeneralNames keyu = GeneralNames.GetInstance(asn1Object); Print(extab + "Subject Alternative Name Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " General Names:"); foreach (GeneralName gen in keyu.GetNames()) { string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " " + tagname + " " + gen.Name); } } else if (oid == X509Extensions.IssuerAlternativeName.Id) { Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(ext.Value); GeneralNames keyu = GeneralNames.GetInstance(asn1Object); Print(extab + "Issuer Alternative Name Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " General Names:"); foreach (GeneralName gen in keyu.GetNames()) { string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " " + tagname + " " + gen.Name); } } else if (oid == X509Extensions.AuthorityInfoAccess.Id) { AuthorityInformationAccess keyu = AuthorityInformationAccess.GetInstance(ext); Print(extab + "Authority Information Access Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Access Descriptions:"); foreach (AccessDescription acc in keyu.GetAccessDescriptions()) { Print(extab + " Method:" + acc.AccessMethod.Id); GeneralName gen = acc.AccessLocation; string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " Access Location:" + tagname + "=" + gen.Name); } } else if (oid == X509Extensions.SubjectInfoAccess.Id) { AuthorityInformationAccess keyu = AuthorityInformationAccess.GetInstance(ext); Print(extab + "Subject Information Access Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Access Descriptions:"); foreach (AccessDescription acc in keyu.GetAccessDescriptions()) { Print(extab + " Method:" + acc.AccessMethod.Id); GeneralName gen = acc.AccessLocation; string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " Access Location:" + tagname + "=" + gen.Name); } } else if (oid == X509Extensions.CrlDistributionPoints.Id) { Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(ext.Value); CrlDistPoint keyu = CrlDistPoint.GetInstance(asn1Object); Print(extab + "Crl Distribution Points Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Distribution Points:"); foreach (DistributionPoint acc in keyu.GetDistributionPoints()) { if (acc.Reasons != null) { Print(extab + " Reasons:" + acc.Reasons.GetString()); } else { Print(extab + " Reasons:Null"); } if (acc.CrlIssuer != null) { Print(extab + " Crl Issuer:"); foreach (GeneralName gen in acc.CrlIssuer.GetNames()) { string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " " + tagname + ": " + gen.Name); } } else { Print(extab + " Crl Issuer:Null"); } Print(extab + " Distribution Point Name:"); if (acc.DistributionPointName.PointType == DistributionPointName.FullName) { GeneralNames sgen = GeneralNames.GetInstance(acc.DistributionPointName.Name); foreach (GeneralName gen in sgen.GetNames()) { string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " " + tagname + " " + gen.Name); } } else { Print(extab + " Not Supported by OCT"); } } } } // Signature Print(" Signature Algorithm: " + cer.SignatureAlgorithm.FriendlyName + " " + (CERT.GetSignature().Length * 8) + " bit"); Print(CERT.GetSignature(), " "); Print(" SHA1 Fingerprint : "); Print(Sha1(CERT.GetEncoded()), " "); Print(" SHA224 Fingerprint : "); Print(Sha224(CERT.GetEncoded()), " "); Print(" SHA256 Fingerprint : "); Print(Sha256(CERT.GetEncoded()), " "); Print(" SHA384 Fingerprint : "); Print(Sha384(CERT.GetEncoded()), " "); Print(" SHA512 Fingerprint : "); Print(Sha512(CERT.GetEncoded()), " "); Print(" MD5 Fingerprint : "); Print(MD5(CERT.GetEncoded()), " "); Print("Issuer Base64:" + Convert.ToBase64String(CERT.IssuerDN.GetDerEncoded())); Print("Subject Base64:" + Convert.ToBase64String(CERT.SubjectDN.GetDerEncoded())); Print("Serial Base64:" + Convert.ToBase64String(CERT.SerialNumber.ToByteArray())); if (outputfile == "stdout") { Console.Read(); } else { str.Close(); } }
public string CreateAndStoreNewClientCertificate(string subjectName, string pvkPass, X509Certificate2 issuer) { X509V3CertificateGenerator generator = new X509V3CertificateGenerator(); // Generate pseudo random number var randomGen = new CryptoApiRandomGenerator(); var random = new SecureRandom(randomGen); // Set certificate serial number var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random); generator.SetSerialNumber(serialNumber); // Set certificate subject name var subjectDN = new X509Name(subjectName); generator.SetSubjectDN(subjectDN); // Set issuer subject name var issuerDN = new X509Name(issuer.Subject); generator.SetIssuerDN(issuerDN); // Set certificate validity var notBefore = DateTime.UtcNow.Date; generator.SetNotBefore(notBefore); generator.SetNotAfter(notBefore.AddYears(2)); // Generate new RSA key pair for certificate var keyGeneratorParameters = new KeyGenerationParameters(random, RSAKeyStrength); var keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(keyGeneratorParameters); var subjectKeyPair = keyPairGenerator.GenerateKeyPair(); // Import public key into generator generator.SetPublicKey(subjectKeyPair.Public); var issuerKeyPair = DotNetUtilities.GetKeyPair(issuer.PrivateKey); // Get key pair from .net issuer certificate //var issuerKeyPair = DotNetUtilities.GetKeyPair(issuer.PrivateKey); var issuerSerialNumber = new BigInteger(issuer.GetSerialNumber()); // Sign CA key with serial var caKeyIdentifier = new AuthorityKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerKeyPair.Public), new GeneralNames(new GeneralName(issuerDN)), issuerSerialNumber); generator.AddExtension( X509Extensions.AuthorityKeyIdentifier.Id, false, caKeyIdentifier); // Create signature factory to sign new cert ISignatureFactory signatureFactory = new Asn1SignatureFactory(SignatureAlgorithm, issuerKeyPair.Private); // Generate new bouncy castle certificate signed by issuer var newCertificate = generator.Generate(signatureFactory); var store = new Pkcs12Store(); string friendlyName = newCertificate.SubjectDN.ToString().Split('=')[1]; var certificateEntry = new X509CertificateEntry(newCertificate); // Set certificate store.SetCertificateEntry(friendlyName, certificateEntry); // Set private key store.SetKeyEntry( friendlyName, new AsymmetricKeyEntry(subjectKeyPair.Private), new X509CertificateEntry[] { certificateEntry }); var privatePath = @".\certs\" + $"{friendlyName}.pfx"; var publicPath = @".\certs\" + $"{friendlyName}.cer"; using (var stream = new MemoryStream()) { // Convert bouncy castle cert => .net cert store.Save(stream, pvkPass.ToCharArray(), random); var dotNetCertificate = new X509Certificate2( stream.ToArray(), pvkPass, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); // Extract public part to store in server storage var publicCert = dotNetCertificate.Export(X509ContentType.Cert); // Extract private parameters to export into .pfx for distribution var privateCert = dotNetCertificate.Export(X509ContentType.Pfx, pvkPass); dotNetCertificate.Reset(); dotNetCertificate.Import(publicCert); // Store public cert info in storage using (var storage = new X509Store(StoreName.My, StoreLocation.LocalMachine)) { storage.Open(OpenFlags.ReadWrite); storage.Add(dotNetCertificate); storage.Close(); } dotNetCertificate.Dispose(); // Write private parameters to .pfx file to install at client File.WriteAllBytes(privatePath, privateCert); File.WriteAllBytes(publicPath, publicCert); } return(privatePath); }
public void CheckCertificate( int id, byte[] cert) { Asn1Object seq = Asn1Object.FromByteArray(cert); string dump = Asn1Dump.DumpAsString(seq); X509CertificateStructure obj = X509CertificateStructure.GetInstance(seq); TbsCertificateStructure tbsCert = obj.TbsCertificate; if (!tbsCert.Subject.ToString().Equals(subjects[id - 1])) { Fail("failed subject test for certificate id " + id + " got " + tbsCert.Subject.ToString()); } if (tbsCert.Version >= 3) { X509Extensions ext = tbsCert.Extensions; if (ext != null) { foreach (DerObjectIdentifier oid in ext.ExtensionOids) { X509Extension extVal = ext.GetExtension(oid); Asn1Object extObj = Asn1Object.FromByteArray(extVal.Value.GetOctets()); if (oid.Equals(X509Extensions.SubjectKeyIdentifier)) { SubjectKeyIdentifier.GetInstance(extObj); } else if (oid.Equals(X509Extensions.KeyUsage)) { KeyUsage.GetInstance(extObj); } else if (oid.Equals(X509Extensions.ExtendedKeyUsage)) { ExtendedKeyUsage ku = ExtendedKeyUsage.GetInstance(extObj); Asn1Sequence sq = (Asn1Sequence)ku.ToAsn1Object(); for (int i = 0; i != sq.Count; i++) { KeyPurposeID.GetInstance(sq[i]); } } else if (oid.Equals(X509Extensions.SubjectAlternativeName)) { GeneralNames gn = GeneralNames.GetInstance(extObj); Asn1Sequence sq = (Asn1Sequence)gn.ToAsn1Object(); for (int i = 0; i != sq.Count; i++) { GeneralName.GetInstance(sq[i]); } } else if (oid.Equals(X509Extensions.IssuerAlternativeName)) { GeneralNames gn = GeneralNames.GetInstance(extObj); Asn1Sequence sq = (Asn1Sequence)gn.ToAsn1Object(); for (int i = 0; i != sq.Count; i++) { GeneralName.GetInstance(sq[i]); } } else if (oid.Equals(X509Extensions.CrlDistributionPoints)) { CrlDistPoint p = CrlDistPoint.GetInstance(extObj); DistributionPoint[] points = p.GetDistributionPoints(); for (int i = 0; i != points.Length; i++) { // do nothing } } else if (oid.Equals(X509Extensions.CertificatePolicies)) { Asn1Sequence cp = (Asn1Sequence)extObj; for (int i = 0; i != cp.Count; i++) { PolicyInformation.GetInstance(cp[i]); } } else if (oid.Equals(X509Extensions.AuthorityKeyIdentifier)) { AuthorityKeyIdentifier.GetInstance(extObj); } else if (oid.Equals(X509Extensions.BasicConstraints)) { BasicConstraints.GetInstance(extObj); } else { //Console.WriteLine(oid.Id); } } } } }