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); }
public AttributeCertificateHolder(X509Certificate cert) { X509Name issuerX509Principal; try { issuerX509Principal = PrincipalUtilities.GetIssuerX509Principal(cert); } catch (Exception ex) { throw new CertificateParsingException(ex.Message); } holder = new Holder(new IssuerSerial(GenerateGeneralNames(issuerX509Principal), new DerInteger(cert.SerialNumber))); }
// 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); }