private X509Crl CreateCrl(X509Certificate signingCertificate) { EnsureInitialized(); _crlGenerator.Reset(); DateTime now = DateTime.UtcNow; _crlGenerator.SetThisUpdate(now); _crlGenerator.SetNextUpdate(now.Add(_crlValidityPeriod)); _crlGenerator.SetIssuerDN(PrincipalUtilities.GetSubjectX509Principal(signingCertificate)); _crlGenerator.SetSignatureAlgorithm(_signatureAlthorithm); _crlGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(signingCertificate)); BigInteger crlNumber = new BigInteger(7 /*bits for the number*/, _random).Abs(); _crlGenerator.AddExtension(X509Extensions.CrlNumber, false, new CrlNumber(crlNumber)); foreach (var kvp in _revokedCertificates) { _crlGenerator.AddCrlEntry(new BigInteger(kvp.Key, 16), kvp.Value, CrlReason.CessationOfOperation); } X509Crl crl = _crlGenerator.Generate(_authorityKeyPair.Private, _random); crl.Verify(_authorityKeyPair.Public); Trace.WriteLine(string.Format("[CertificateGenerator] has created a Certificate Revocation List :")); Trace.WriteLine(string.Format(" {0} = {1}", "Issuer", crl.IssuerDN)); Trace.WriteLine(string.Format(" {0} = {1}", "CRL Number", crlNumber)); return(crl); }
private X509Certificate IssueCertificate( IssueCertificateOptions options, Action <X509V3CertificateGenerator> customizeCertificate) { var serialNumber = _nextSerialNumber; var issuerName = PrincipalUtilities.GetSubjectX509Principal(Certificate); var notAfter = options.NotAfter.UtcDateTime; // An issued certificate should not have a validity period beyond the issuer's validity period. if (notAfter > Certificate.NotAfter) { notAfter = Certificate.NotAfter; } var signatureFactory = new Asn1SignatureFactory(options.SignatureAlgorithmName, options.IssuerPrivateKey ?? KeyPair.Private); var certificate = CreateCertificate( options.KeyPair.Public, signatureFactory, serialNumber, issuerName, options.SubjectName, options.NotBefore.UtcDateTime, notAfter, options.CustomizeCertificate ?? customizeCertificate); _nextSerialNumber = _nextSerialNumber.Add(BigInteger.One); _issuedCertificates.Add(certificate.SerialNumber, certificate); return(certificate); }
private static CertID CreateCertID( AlgorithmIdentifier hashAlg, X509Certificate issuerCert, DerInteger serialNumber) { try { String hashAlgorithm = hashAlg.Algorithm.Id; X509Name issuerName = PrincipalUtilities.GetSubjectX509Principal(issuerCert); byte[] issuerNameHash = DigestUtilities.CalculateDigest( hashAlgorithm, issuerName.GetEncoded()); AsymmetricKeyParameter issuerKey = issuerCert.GetPublicKey(); SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerKey); byte[] issuerKeyHash = DigestUtilities.CalculateDigest( hashAlgorithm, info.PublicKeyData.GetBytes()); return(new CertID(hashAlg, new DerOctetString(issuerNameHash), new DerOctetString(issuerKeyHash), serialNumber)); } catch (Exception e) { throw new OcspException("problem creating ID: " + e, e); } }
private IX509AttributeCertificate CreateAttrCert() { // CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); // X509Certificate iCert = (X509Certificate) fact // .generateCertificate(new ByteArrayInputStream(holderCert)); X509Certificate iCert = new X509CertificateParser().ReadCertificate(holderCert); // // a sample key pair. // // RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec( // new BigInteger( // "b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", // 16), new BigInteger("11", 16)); // // set up the keys // // KeyFactory kFact = KeyFactory.getInstance("RSA", "BC"); // PrivateKey privKey = kFact.generatePrivate(RsaPrivateKeySpec); IAsymmetricKeyParameter privKey = RsaPrivateKeySpec; X509V2AttributeCertificateGenerator gen = new X509V2AttributeCertificateGenerator(); // the actual attributes GeneralName roleName = new GeneralName(GeneralName.Rfc822Name, "*****@*****.**"); Asn1EncodableVector roleSyntax = new Asn1EncodableVector(roleName); // roleSyntax OID: 2.5.24.72 X509Attribute attributes = new X509Attribute("2.5.24.72", new DerSequence(roleSyntax)); gen.AddAttribute(attributes); gen.SetHolder(new AttributeCertificateHolder(PrincipalUtilities.GetSubjectX509Principal(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"); Target targetName = new Target( Target.Choice.Name, new GeneralName(GeneralName.DnsName, "www.test.com")); Target targetGroup = new Target( Target.Choice.Group, new GeneralName(GeneralName.DirectoryName, "o=Test, ou=Test")); Target[] targets = new Target[] { targetName, targetGroup }; TargetInformation targetInformation = new TargetInformation(targets); gen.AddExtension(X509Extensions.TargetInformation.Id, true, targetInformation); return(gen.Generate(privKey)); }
public bool Match(X509Certificate x509Cert) { try { if (holder.BaseCertificateID != null) { return(holder.BaseCertificateID.Serial.Value.Equals(x509Cert.SerialNumber) && MatchesDN(PrincipalUtilities.GetIssuerX509Principal(x509Cert), holder.BaseCertificateID.Issuer)); } if (holder.EntityName != null && MatchesDN(PrincipalUtilities.GetSubjectX509Principal(x509Cert), holder.EntityName)) { return(true); } if (holder.ObjectDigestInfo != null) { IDigest digest = null; try { digest = DigestUtilities.GetDigest(DigestAlgorithm); } catch (Exception) { return(false); } switch (DigestedObjectType) { case 0: { byte[] encoded2 = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(x509Cert.GetPublicKey()).GetEncoded(); digest.BlockUpdate(encoded2, 0, encoded2.Length); break; } case 1: { byte[] encoded = x509Cert.GetEncoded(); digest.BlockUpdate(encoded, 0, encoded.Length); break; } } if (!Arrays.AreEqual(DigestUtilities.DoFinal(digest), GetObjectDigest())) { return(false); } } } catch (CertificateEncodingException) { return(false); } return(false); }
private static CertID CreateCertID(AlgorithmIdentifier hashAlg, X509Certificate issuerCert, DerInteger serialNumber) { try { string algorithm = hashAlg.Algorithm.Id; X509Name subjectX509Principal = PrincipalUtilities.GetSubjectX509Principal(issuerCert); byte[] str = DigestUtilities.CalculateDigest(algorithm, subjectX509Principal.GetEncoded()); AsymmetricKeyParameter publicKey = issuerCert.GetPublicKey(); SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey); byte[] str2 = DigestUtilities.CalculateDigest(algorithm, subjectPublicKeyInfo.PublicKeyData.GetBytes()); return(new CertID(hashAlg, new DerOctetString(str), new DerOctetString(str2), serialNumber)); } catch (Exception ex) { throw new OcspException("problem creating ID: " + ex, ex); } }
public X509Crl Update( string algorithm, X509Crl existingCrl, X509Certificate[] certificates, X509Certificate caCert, AsymmetricCipherKeyPair caKey, DateTime thisUpdate, DateTime nextUpdate, int /*CrlReason*/ reason) { var crlGenerator = new X509V2CrlGenerator(); crlGenerator.SetIssuerDN(PrincipalUtilities.GetSubjectX509Principal(caCert)); crlGenerator.SetThisUpdate(thisUpdate); crlGenerator.SetNextUpdate(nextUpdate); var signatureFactory = new Asn1SignatureFactory( algorithm, caKey.Private); crlGenerator.AddCrl(existingCrl); if (!certificates.IsNullOrEmpty()) { foreach (X509Certificate certificate in certificates) { // a ver... a questão da CrlRerason... pode ser individual ?!?!?! crlGenerator.AddCrlEntry(certificate.SerialNumber, thisUpdate, reason); } } crlGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); BigInteger existingCrlNumber = DerInteger.GetInstance( Asn1Object.FromByteArray(existingCrl.GetExtensionValue(X509Extensions.CrlNumber).GetOctets()) ).PositiveValue; crlGenerator.AddExtension( X509Extensions.CrlNumber, false, new CrlNumber(existingCrlNumber.Add(BigInteger.One))); return(crlGenerator.Generate(signatureFactory)); }
private X509Crl CreateCrl(X509Certificate signingCertificate) { EnsureInitialized(); s_crlGenerator.Reset(); DateTime now = DateTime.UtcNow; DateTime updateTime = now.Subtract(_crlValidityGracePeriodEnd); // Ensure that the update time for the CRL is no greater than the earliest time that the CA is valid for if (_defaultValidityNotBefore > now.Subtract(_crlValidityGracePeriodEnd)) { updateTime = _defaultValidityNotBefore; } s_crlGenerator.SetThisUpdate(updateTime); //There is no need to update CRL. s_crlGenerator.SetNextUpdate(now.Add(ValidityPeriod)); s_crlGenerator.SetIssuerDN(PrincipalUtilities.GetSubjectX509Principal(signingCertificate)); s_crlGenerator.SetSignatureAlgorithm(_signatureAlthorithm); s_crlGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(signingCertificate)); BigInteger crlNumber = new BigInteger(64 /*bits for the number*/, _random).Abs(); s_crlGenerator.AddExtension(X509Extensions.CrlNumber, false, new CrlNumber(crlNumber)); foreach (var kvp in s_revokedCertificates) { s_crlGenerator.AddCrlEntry(new BigInteger(kvp.Key, 16), kvp.Value, CrlReason.CessationOfOperation); } X509Crl crl = s_crlGenerator.Generate(_authorityKeyPair.Private, _random); crl.Verify(_authorityKeyPair.Public); Trace.WriteLine(string.Format("[CertificateGenerator] has created a Certificate Revocation List :")); Trace.WriteLine(string.Format(" {0} = {1}", "Issuer", crl.IssuerDN)); Trace.WriteLine(string.Format(" {0} = {1}", "CRL Number", crlNumber)); return(crl); }
public static X509Certificate GenerateEndEntityCert( IAsymmetricKeyParameter entityKey, IAsymmetricKeyParameter caKey, X509Certificate caCert) { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.SetSerialNumber(BigInteger.One); certGen.SetIssuerDN(PrincipalUtilities.GetSubjectX509Principal(caCert)); certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50)); certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50)); certGen.SetSubjectDN(new X509Name("CN=Test End Certificate")); certGen.SetPublicKey(entityKey); certGen.SetSignatureAlgorithm("SHA256WithRSAEncryption"); certGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); certGen.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(entityKey)); certGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyEncipherment)); return(certGen.Generate(caKey)); }
/** * create from an issuer certificate and the serial number of the * certificate it signed. * @exception OcspException if any problems occur creating the id fields. */ public CertificateID( string hashAlgorithm, X509Certificate issuerCert, BigInteger number) { try { IDigest digest = DigestUtilities.GetDigest(hashAlgorithm); AlgorithmIdentifier hashAlg = new AlgorithmIdentifier( new DerObjectIdentifier(hashAlgorithm), DerNull.Instance); X509Name issuerName = PrincipalUtilities.GetSubjectX509Principal(issuerCert); byte[] encodedIssuerName = issuerName.GetEncoded(); digest.BlockUpdate(encodedIssuerName, 0, encodedIssuerName.Length); byte[] hash = DigestUtilities.DoFinal(digest); Asn1OctetString issuerNameHash = new DerOctetString(hash); AsymmetricKeyParameter issuerKey = issuerCert.GetPublicKey(); SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerKey); byte[] encodedPublicKey = info.PublicKeyData.GetBytes(); digest.BlockUpdate(encodedPublicKey, 0, encodedPublicKey.Length); hash = DigestUtilities.DoFinal(digest); Asn1OctetString issuerKeyHash = new DerOctetString(hash); DerInteger serialNumber = new DerInteger(number); this.id = new CertID(hashAlg, issuerNameHash, issuerKeyHash, serialNumber); } catch (Exception e) { throw new OcspException("problem creating ID: " + e, e); } }
public static X509Crl CreateCrl( X509Certificate caCert, IAsymmetricKeyParameter caKey, IBigInteger serialNumber) { X509V2CrlGenerator crlGen = new X509V2CrlGenerator(); DateTime now = DateTime.UtcNow; // BigInteger revokedSerialNumber = BigInteger.Two; crlGen.SetIssuerDN(PrincipalUtilities.GetSubjectX509Principal(caCert)); crlGen.SetThisUpdate(now); crlGen.SetNextUpdate(now.AddSeconds(100)); crlGen.SetSignatureAlgorithm("SHA256WithRSAEncryption"); crlGen.AddCrlEntry(serialNumber, now, CrlReason.PrivilegeWithdrawn); crlGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); crlGen.AddExtension(X509Extensions.CrlNumber, false, new CrlNumber(BigInteger.One)); return(crlGen.Generate(caKey)); }
// LISTA vazia ..... public X509Crl Create( string algorithm, X509Certificate caCert, AsymmetricCipherKeyPair caKey, DateTime thisUpdate, DateTime nextUpdate) { var crlGenerator = new X509V2CrlGenerator(); crlGenerator.SetIssuerDN(PrincipalUtilities.GetSubjectX509Principal(caCert)); crlGenerator.SetThisUpdate(thisUpdate); crlGenerator.SetNextUpdate(nextUpdate); var signatureFactory = new Asn1SignatureFactory( algorithm, caKey.Private); crlGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); crlGenerator.AddExtension(X509Extensions.CrlNumber, false, new CrlNumber(BigInteger.One)); return(crlGenerator.Generate(signatureFactory)); }
// 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); }
public override void PerformTest() { X509CertificateParser certParser = new X509CertificateParser(); X509CrlParser crlParser = new X509CrlParser(); X509Certificate rootCert = certParser.ReadCertificate(CertPathTest.rootCertBin); X509Certificate interCert = certParser.ReadCertificate(CertPathTest.interCertBin); X509Certificate finalCert = certParser.ReadCertificate(CertPathTest.finalCertBin); X509Crl rootCrl = crlParser.ReadCrl(CertPathTest.rootCrlBin); X509Crl interCrl = crlParser.ReadCrl(CertPathTest.interCrlBin); // Testing CollectionCertStore generation from List IList certList = new ArrayList(); certList.Add(rootCert); certList.Add(interCert); certList.Add(finalCert); IX509Store certStore = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(certList)); // set default to be the same as for SUN X500 name X509Name.DefaultReverse = true; // Searching for rootCert by subjectDN X509CertStoreSelector targetConstraints = new X509CertStoreSelector(); targetConstraints.Subject = PrincipalUtilities.GetSubjectX509Principal(rootCert); IList certs = new ArrayList(certStore.GetMatches(targetConstraints)); if (certs.Count != 1 || !certs.Contains(rootCert)) { Fail("rootCert not found by subjectDN"); } // Searching for rootCert by subjectDN encoded as byte targetConstraints = new X509CertStoreSelector(); targetConstraints.Subject = PrincipalUtilities.GetSubjectX509Principal(rootCert); certs = new ArrayList(certStore.GetMatches(targetConstraints)); if (certs.Count != 1 || !certs.Contains(rootCert)) { Fail("rootCert not found by encoded subjectDN"); } X509Name.DefaultReverse = false; // Searching for rootCert by public key encoded as byte targetConstraints = new X509CertStoreSelector(); targetConstraints.SubjectPublicKey = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(rootCert.GetPublicKey()); certs = new ArrayList(certStore.GetMatches(targetConstraints)); if (certs.Count != 1 || !certs.Contains(rootCert)) { Fail("rootCert not found by encoded public key"); } // Searching for interCert by issuerDN targetConstraints = new X509CertStoreSelector(); targetConstraints.Issuer = PrincipalUtilities.GetSubjectX509Principal(rootCert); certs = new ArrayList(certStore.GetMatches(targetConstraints)); if (certs.Count != 2) { Fail("did not found 2 certs"); } if (!certs.Contains(rootCert)) { Fail("rootCert not found"); } if (!certs.Contains(interCert)) { Fail("interCert not found"); } // Searching for rootCrl by issuerDN IList crlList = new ArrayList(); crlList.Add(rootCrl); crlList.Add(interCrl); IX509Store store = X509StoreFactory.Create( "CRL/Collection", new X509CollectionStoreParameters(crlList)); X509CrlStoreSelector targetConstraintsCRL = new X509CrlStoreSelector(); ArrayList issuers = new ArrayList(); issuers.Add(rootCrl.IssuerDN); targetConstraintsCRL.Issuers = issuers; IList crls = new ArrayList(store.GetMatches(targetConstraintsCRL)); if (crls.Count != 1 || !crls.Contains(rootCrl)) { Fail("rootCrl not found"); } crls = new ArrayList(certStore.GetMatches(targetConstraintsCRL)); if (crls.Count != 0) { Fail("error using wrong selector (CRL)"); } certs = new ArrayList(store.GetMatches(targetConstraints)); if (certs.Count != 0) { Fail("error using wrong selector (certs)"); } // Searching for attribute certificates X509V2AttributeCertificate attrCert = new X509V2AttributeCertificate(AttrCertTest.attrCert); IX509AttributeCertificate attrCert2 = new X509V2AttributeCertificate(AttrCertTest.certWithBaseCertificateID); IList attrList = new ArrayList(); attrList.Add(attrCert); attrList.Add(attrCert2); store = X509StoreFactory.Create( "AttributeCertificate/Collection", new X509CollectionStoreParameters(attrList)); X509AttrCertStoreSelector attrSelector = new X509AttrCertStoreSelector(); attrSelector.Holder = attrCert.Holder; if (!attrSelector.Holder.Equals(attrCert.Holder)) { Fail("holder get not correct"); } IList attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert)) { Fail("attrCert not found on holder"); } attrSelector.Holder = attrCert2.Holder; if (attrSelector.Holder.Equals(attrCert.Holder)) { Fail("holder get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert2)) { Fail("attrCert2 not found on holder"); } attrSelector = new X509AttrCertStoreSelector(); attrSelector.Issuer = attrCert.Issuer; if (!attrSelector.Issuer.Equals(attrCert.Issuer)) { Fail("issuer get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert)) { Fail("attrCert not found on issuer"); } attrSelector.Issuer = attrCert2.Issuer; if (attrSelector.Issuer.Equals(attrCert.Issuer)) { Fail("issuer get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert2)) { Fail("attrCert2 not found on issuer"); } attrSelector = new X509AttrCertStoreSelector(); attrSelector.AttributeCert = attrCert; if (!attrSelector.AttributeCert.Equals(attrCert)) { Fail("attrCert get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert)) { Fail("attrCert not found on attrCert"); } attrSelector = new X509AttrCertStoreSelector(); attrSelector.SerialNumber = attrCert.SerialNumber; if (!attrSelector.SerialNumber.Equals(attrCert.SerialNumber)) { Fail("serial number get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert)) { Fail("attrCert not found on serial number"); } attrSelector = (X509AttrCertStoreSelector)attrSelector.Clone(); if (!attrSelector.SerialNumber.Equals(attrCert.SerialNumber)) { Fail("serial number get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert)) { Fail("attrCert not found on serial number"); } attrSelector = new X509AttrCertStoreSelector(); attrSelector.AttributeCertificateValid = new DateTimeObject(attrCert.NotBefore); if (attrSelector.AttributeCertificateValid.Value != attrCert.NotBefore) { Fail("valid get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert)) { Fail("attrCert not found on valid"); } attrSelector = new X509AttrCertStoreSelector(); attrSelector.AttributeCertificateValid = new DateTimeObject(attrCert.NotBefore.AddMilliseconds(-100)); attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 0) { Fail("attrCert found on before"); } attrSelector.AttributeCertificateValid = new DateTimeObject(attrCert.NotAfter.AddMilliseconds(100)); attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 0) { Fail("attrCert found on after"); } attrSelector.SerialNumber = BigInteger.ValueOf(10000); attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 0) { Fail("attrCert found on wrong serial number"); } attrSelector.AttributeCert = null; attrSelector.AttributeCertificateValid = null; attrSelector.Holder = null; attrSelector.Issuer = null; attrSelector.SerialNumber = null; if (attrSelector.AttributeCert != null) { Fail("null attrCert"); } if (attrSelector.AttributeCertificateValid != null) { Fail("null attrCertValid"); } if (attrSelector.Holder != null) { Fail("null attrCert holder"); } if (attrSelector.Issuer != null) { Fail("null attrCert issuer"); } if (attrSelector.SerialNumber != null) { Fail("null attrCert serial"); } attrs = new ArrayList(certStore.GetMatches(attrSelector)); if (attrs.Count != 0) { Fail("error using wrong selector (attrs)"); } certPairTest(); }
// 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); }
public X509Certificate IssueCertificate(IssueCertificateOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } var serialNumber = _nextSerialNumber; var issuerName = PrincipalUtilities.GetSubjectX509Principal(Certificate); Action <X509V3CertificateGenerator> customizeCertificate; if (options.CustomizeCertificate == null) { customizeCertificate = generator => { generator.AddExtension( X509Extensions.AuthorityInfoAccess, critical: false, extensionValue: new DerSequence( new AccessDescription(AccessDescription.IdADOcsp, new GeneralName(GeneralName.UniformResourceIdentifier, OcspResponderUri.OriginalString)), new AccessDescription(AccessDescription.IdADCAIssuers, new GeneralName(GeneralName.UniformResourceIdentifier, CertificateUri.OriginalString)))); generator.AddExtension( X509Extensions.AuthorityKeyIdentifier, critical: false, extensionValue: new AuthorityKeyIdentifierStructure(Certificate)); generator.AddExtension( X509Extensions.SubjectKeyIdentifier, critical: false, extensionValue: new SubjectKeyIdentifierStructure(options.PublicKey)); generator.AddExtension( X509Extensions.BasicConstraints, critical: true, extensionValue: new BasicConstraints(cA: false)); }; } else { customizeCertificate = options.CustomizeCertificate; } var notAfter = options.NotAfter.UtcDateTime; // An issued certificate should not have a validity period beyond the issuer's validity period. if (notAfter > Certificate.NotAfter) { notAfter = Certificate.NotAfter; } var certificate = CreateCertificate( options.PublicKey, KeyPair.Private, serialNumber, issuerName, options.SubjectName, options.NotBefore.UtcDateTime, notAfter, customizeCertificate); _nextSerialNumber = _nextSerialNumber.Add(BigInteger.One); _issuedCertificates.Add(certificate.SerialNumber, certificate); return(certificate); }
/** * we generate an intermediate certificate signed by our CA */ public static X509CertificateEntry CreateIntermediateCert( AsymmetricKeyParameter pubKey, AsymmetricKeyParameter caPrivKey, X509Certificate caCert) { // // subject name table. // IDictionary attrs = new Hashtable(); IList order = new ArrayList(); attrs.Add(X509Name.C, "AU"); attrs.Add(X509Name.O, "The Legion of the Bouncy Castle"); attrs.Add(X509Name.OU, "Bouncy Intermediate Certificate"); attrs.Add(X509Name.EmailAddress, "*****@*****.**"); order.Add(X509Name.C); order.Add(X509Name.O); order.Add(X509Name.OU); order.Add(X509Name.EmailAddress); // // create the certificate - version 3 // v3CertGen.Reset(); v3CertGen.SetSerialNumber(BigInteger.Two); v3CertGen.SetIssuerDN(PrincipalUtilities.GetSubjectX509Principal(caCert)); v3CertGen.SetNotBefore(DateTime.UtcNow.AddMonths(-1)); v3CertGen.SetNotAfter(DateTime.UtcNow.AddMonths(1)); v3CertGen.SetSubjectDN(new X509Name(order, attrs)); v3CertGen.SetPublicKey(pubKey); v3CertGen.SetSignatureAlgorithm("SHA1WithRSAEncryption"); // // extensions // v3CertGen.AddExtension( X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pubKey)); v3CertGen.AddExtension( X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); v3CertGen.AddExtension( X509Extensions.BasicConstraints, true, new BasicConstraints(0)); X509Certificate cert = v3CertGen.Generate(caPrivKey); cert.CheckValidity(DateTime.UtcNow); cert.Verify(caCert.GetPublicKey()); // PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier)cert; IDictionary bagAttr = new Hashtable(); // // this is actually optional - but if you want to have control // over setting the friendly name this is the way to do it... // // bagAttr.setBagAttribute( // PKCSObjectIdentifiers.pkcs_9_at_friendlyName, // new DERBMPString("Bouncy Intermediate Certificate")); bagAttr.Add(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id, new DerBmpString("Bouncy Intermediate Certificate")); return(new X509CertificateEntry(cert, bagAttr)); }