public byte[] GetCrl(RevocationStatus status) { if (status == RevocationStatus.Unknown | Issuer == null) { return(new byte[0]); } var generator = new X509V2CrlGenerator(); generator.SetIssuerDN(new X509Name(Issuer.SubjectName.Name)); generator.SetThisUpdate(DateTime.Now.AddDays(-1)); generator.SetNextUpdate(DateTime.Now.AddDays(1)); generator.SetSignatureAlgorithm("SHA256WithRSA"); if (status == RevocationStatus.Revoked) { generator.AddCrlEntry(SerialNumber, DateTime.Now.AddHours(-12), CrlReason.KeyCompromise); } generator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(DotNetUtilities.FromX509Certificate(Issuer))); generator.AddExtension(X509Extensions.CrlNumber, false, new CrlNumber(new BigInteger(new byte[] { 0x01 }))); var crl = generator.Generate(DotNetUtilities.GetKeyPair(Issuer.PrivateKey).Private); return(crl.GetEncoded()); }
private static X509Crl CreateCrl( X509Certificate2 issuerCert, BigInteger version, X509Certificate2 revokedCertificate = null) { var bcIssuerCert = DotNetUtilities.FromX509Certificate(issuerCert); var crlGen = new X509V2CrlGenerator(); crlGen.SetIssuerDN(bcIssuerCert.SubjectDN); crlGen.SetThisUpdate(DateTime.Now); crlGen.SetNextUpdate(DateTime.Now.AddYears(1)); crlGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(bcIssuerCert)); crlGen.AddExtension(X509Extensions.CrlNumber, false, new CrlNumber(version)); if (revokedCertificate != null) { var bcRevokedCert = DotNetUtilities.FromX509Certificate(revokedCertificate); crlGen.AddCrlEntry(bcRevokedCert.SerialNumber, DateTime.Now, CrlReason.PrivilegeWithdrawn); } var random = new SecureRandom(); var issuerPrivateKey = DotNetUtilities.GetKeyPair(issuerCert.PrivateKey).Private; var signatureFactory = new Asn1SignatureFactory(bcIssuerCert.SigAlgOid, issuerPrivateKey, random); var crl = crlGen.Generate(signatureFactory); return(crl); }
public X509Crl CreateCRL() { var caCert = GetRootCert(); var caKey = GetRootKey(); var crlGen = new X509V2CrlGenerator(); crlGen.SetIssuerDN(caCert.IssuerDN); crlGen.SetThisUpdate(DateTime.Now); crlGen.SetNextUpdate(DateTime.Now.AddYears(1)); crlGen.AddCrlEntry(BigInteger.One, DateTime.Now, CrlReason.PrivilegeWithdrawn); crlGen.AddExtension( X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert) ); crlGen.AddExtension( X509Extensions.CrlNumber, false, new CrlNumber(BigInteger.One) ); var crl = GenerateCrl(caKey, crlGen); return(crl); }
/// <exception cref="Org.BouncyCastle.Security.Certificates.CertificateEncodingException"/> public TestCrlBuilder(X509Certificate caCert, DateTime thisUpdate) { X509Name issuerDN = caCert.IssuerDN; crlBuilder = new X509V2CrlGenerator(); crlBuilder.SetIssuerDN(issuerDN); crlBuilder.SetThisUpdate(thisUpdate); }
public X509Crl GenerateCRL() { var coreCApkcs = new Org.BouncyCastle.Pkcs.Pkcs12Store( new FileStream(CAConfig.CoreCACertPath, FileMode.Open, FileAccess.Read), "".ToCharArray() ); string alias = System.Environment.MachineName; Org.BouncyCastle.X509.X509Certificate coreCaCert = coreCApkcs.GetCertificate(alias).Certificate; X509V2CrlGenerator crlGen = new X509V2CrlGenerator(); DateTime now = DateTime.UtcNow; crlGen.SetIssuerDN(coreCaCert.SubjectDN); crlGen.SetThisUpdate(now); crlGen.SetNextUpdate(now.AddMinutes(Constants.CRLNextUpdatedIntervalMinutes)); var revokedPubCerts = _dbContext.PublicCertificates.Where(p => p.IsRevoked); foreach (PublicCertificate pubCert in revokedPubCerts) { crlGen.AddCrlEntry( new Org.BouncyCastle.Math.BigInteger(pubCert.GetSerialNumber().SerialNrBytes), now, Org.BouncyCastle.Asn1.X509.CrlReason.KeyCompromise ); } crlGen.AddExtension( Org.BouncyCastle.Asn1.X509.X509Extensions.AuthorityKeyIdentifier, false, new Org.BouncyCastle.X509.Extension.AuthorityKeyIdentifierStructure( coreCaCert.GetPublicKey() ) ); X509Crl crl = crlGen.Generate( new Org.BouncyCastle.Crypto.Operators.Asn1SignatureFactory( "SHA512WITHRSA", coreCApkcs.GetKey(alias).Key ) ); _logger.LogInformation( string.Format( "Generated CRL at {0} valid for {1} minutes", now, Constants.CRLNextUpdatedIntervalMinutes ) ); return(crl); }
/// <summary> /// Generate and return a new certificate revocation list. /// </summary> /// <returns>Certificate revocation list.</returns> public X509Crl Generate() { var generator = new X509V2CrlGenerator(); // RFC 5280 section 5.1.2.3. Issuer Name generator.SetIssuerDN(IssuerDN); // RFC 5280 section 5.1.2.4. This Update generator.SetThisUpdate(ThisUpdate); // RFC 5280 section 5.1.2.5. Next Update generator.SetNextUpdate(NextUpdate); // RFC 5280 section 5.1.2.6. Revoked Certificates foreach (var revokedCertificate in RevokedCertificates) { var serialNumber = revokedCertificate.Item1; var revocationDate = revokedCertificate.Item2; var reason = CrlReason.PrivilegeWithdrawn; generator.AddCrlEntry(serialNumber, revocationDate, reason); } // RFC 5280 section 5.2.1. Authority Key Identifier generator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(Issuer)); // RFC 5280 section 5.2.2. Issuer Alternative Name var issuerAlternativeName = GetIssuerAlternativeName(); if (issuerAlternativeName != null) { generator.AddExtension(X509Extensions.IssuerAlternativeName, false, issuerAlternativeName); } // RFC 5280 section 5.2.3. CRL Number generator.AddExtension(X509Extensions.CrlNumber, false, new CrlNumber(CrlNumber)); // RFC 5280 section 5.2.7. Authority Information Access var authorityInfoAccess = GetAuthorityInfoAccessEncoded(); if (authorityInfoAccess != null) { generator.AddExtension(X509Extensions.AuthorityInfoAccess, false, authorityInfoAccess); } // Generate and return. return(generator.Generate(new Asn1SignatureFactory(SignatureAlgorithmName, IssuerKeyPair.Private, SecureRandom))); }
public void RevokeUserCertificate(string uid, string cid) { //get root cert X509Certificate rootCert = DotNetUtilities.FromX509Certificate(getRootCert()); //get user cert to be revoked UserCertificate userCert = GetUserCertificate(uid, cid); X509Certificate certToRevoke = new X509CertificateParser().ReadCertificate(userCert.RawCertBody); //parse the last CRL X509CrlParser crlParser = new X509CrlParser(); FileStream fileStream = File.Open(_configuration["CrlPath"], FileMode.Open); X509Crl rootCrl = crlParser.ReadCrl(fileStream); fileStream.Close(); //extract the CRL number Asn1OctetString prevCrlNum = rootCrl.GetExtensionValue(X509Extensions.CrlNumber); Asn1Object obj = X509ExtensionUtilities.FromExtensionValue(prevCrlNum); BigInteger prevCrlNumVal = DerInteger.GetInstance(obj).PositiveValue; //generate new CRL X509V2CrlGenerator crlGenerator = new X509V2CrlGenerator(); crlGenerator.SetIssuerDN(rootCert.SubjectDN); crlGenerator.SetThisUpdate(DateTime.UtcNow); crlGenerator.SetNextUpdate(DateTime.UtcNow.AddDays(10)); crlGenerator.AddCrl(rootCrl); //add the old CRL entries //add the newly revoked certificates crlGenerator.AddCrlEntry(certToRevoke.SerialNumber, DateTime.UtcNow, CrlReason.PrivilegeWithdrawn); //increment CRL Number by 1 crlGenerator.AddExtension("2.5.29.20", false, new CrlNumber(prevCrlNumVal.Add(BigInteger.One))); AsymmetricKeyParameter bouncyCastlePrivateKey = PrivateKeyFactory.CreateKey(getRootPrivateKey().ExportPkcs8PrivateKey()); var sigFactory = new Asn1SignatureFactory("SHA256WITHECDSA", bouncyCastlePrivateKey); X509Crl nextCrl = crlGenerator.Generate(sigFactory); // writePem(_configuration["CrlOldPath"], rootCrl); // write old CRL as backup writePem(_configuration["CrlPath"], nextCrl); //write new CRL // sanity check nextCrl.Verify(rootCert.GetPublicKey()); userCert.Revoked = true; _context.UserCertificates.Update(userCert); }
/// <summary> /// Creates a CRL. /// </summary> /// <param name="crlGen">The CRL generator.</param> protected void createCRL(X509V2CrlGenerator crlGen) { // Set generic fields crlGen.SetSignatureAlgorithm(signatureAlgorithm); crlGen.SetIssuerDN(caCertificate.SubjectDN); DateTime issueDate = DateTime.Now.ToUniversalTime(); DateTime updateDate = issueDate.AddDays(crlInterval); crlGen.SetThisUpdate(issueDate); crlGen.SetNextUpdate(updateDate); // Set serial number crlGen.AddExtension(X509Extensions.CrlNumber, false, new CrlNumber(nextCrlSerial())); // Load the revocation entries Database.PopulateCRL(crlGen, dbFileLocation); }
public static X509Crl GenerateCrl(X509Certificate certificate, ISignatureFactory signatureFactory, int reason) { X509V2CrlGenerator crlGen = new X509V2CrlGenerator(); crlGen.SetIssuerDN(new X509Name("CN=Test CA")); DateTime now = DateTime.Now; crlGen.SetThisUpdate(now); crlGen.SetNextUpdate(DateTime.Now.AddDays(10)); crlGen.AddCrlEntry(certificate.SerialNumber, now, reason); crlGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(certificate)); crlGen.AddExtension(X509Extensions.CrlNumber, false, new CrlNumber(BigInteger.One)); return(crlGen.Generate(signatureFactory)); }
public static X509Crl MakeCrl( AsymmetricCipherKeyPair pair) { X509V2CrlGenerator crlGen = new X509V2CrlGenerator(); DateTime now = DateTime.UtcNow; crlGen.SetIssuerDN(new X509Name("CN=Test CA")); crlGen.SetThisUpdate(now); crlGen.SetNextUpdate(now.AddSeconds(100)); crlGen.SetSignatureAlgorithm("SHA256WithRSAEncryption"); crlGen.AddCrlEntry(BigInteger.One, now, CrlReason.PrivilegeWithdrawn); crlGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(pair.Public)); return(crlGen.Generate(pair.Private)); }
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); }
/// <summary> /// Publishes the crl /// </summary> public void PublishCrl() { if (_revoked == null) { return; //TODO: may be show a messagebox or something? } Pkcs12Store store = LoadCAPfx(KeyStorePassword); if (!store.ContainsAlias(CaAlias) || !store.IsEntryOfType(CaAlias, typeof(AsymmetricKeyEntry))) { return; } AsymmetricKeyParameter key = store.GetKey(CaAlias).Key; X509Certificate caCert = store.GetCertificate(CaAlias).Certificate; var crlNumber = new BigInteger(ReadCrlSerialNumber(), SerialNumberRadix); var crlGen = new X509V2CrlGenerator(); crlGen.SetIssuerDN(caCert.SubjectDN); //crlGen.SetNextUpdate(); crlGen.SetSignatureAlgorithm(caCert.SigAlgName.Replace("-", "")); crlGen.SetThisUpdate(DateTime.UtcNow); crlGen.SetNextUpdate(DateTime.UtcNow.AddHours(CrlFrequency)); crlGen.AddExtension(X509Extensions.CrlNumber, false, new CrlNumber(crlNumber)); crlGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); //crlGen.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.KeyAgreement | KeyUsage.CrlSign | KeyUsage.DataEncipherment | KeyUsage.DecipherOnly | KeyUsage.EncipherOnly | KeyUsage.KeyEncipherment | KeyUsage.NonRepudiation)); foreach (RevokedSerial rs in _revoked.RevokedSerialCollection) { crlGen.AddCrlEntry(new BigInteger(rs.Serial), rs.RevocationDate, rs.Reason); } X509Crl crl = crlGen.Generate(key); string crlEncoded = PemUtilities.Encode(crl); File.WriteAllText(CrlFilePath, crlEncoded); IncrementCrlSerial(); }
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)); }
/// <summary> /// Generate CRL. /// </summary> /// <returns>Result.</returns> public X509Crl Generate() { var signer = DotNetUtilities.FromX509Certificate(signerCertificate.Certificate); ISignatureFactory signatureFactory = new Asn1SignatureFactory(SignatureAlgorithm, signerCertificate.KeyPair.Private, random); crlGenerator.SetIssuerDN(signer.IssuerDN); crlGenerator.SetThisUpdate(DateTime.Now); crlGenerator.SetNextUpdate(DateTime.Now.AddYears(1)); crlGenerator.AddCrlEntry(BigInteger.One, DateTime.Now, CrlReason.PrivilegeWithdrawn); crlGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(signer)); var crlNumber = new BigInteger(DateTime.UtcNow.ToString("yyyyMMddHHmm")); crlGenerator.AddExtension(X509Extensions.CrlNumber, false, new CrlNumber(crlNumber)); X509Crl crlTemp = crlGenerator.Generate(signatureFactory); return(crlTemp); }
/// <summary> /// Revoke the certificate. /// The CRL number is increased by one and the new CRL is returned. /// </summary> public static X509CRL RevokeCertificate( X509Certificate2 issuerCertificate, List <X509CRL> issuerCrls, X509Certificate2Collection revokedCertificates ) { if (!issuerCertificate.HasPrivateKey) { throw new ServiceResultException(StatusCodes.BadCertificateInvalid, "Issuer certificate has no private key, cannot revoke certificate."); } using (var cfrg = new CertificateFactoryRandomGenerator()) { // cert generators SecureRandom random = new SecureRandom(cfrg); BigInteger crlSerialNumber = BigInteger.Zero; Org.BouncyCastle.X509.X509Certificate bcCertCA = new X509CertificateParser().ReadCertificate(issuerCertificate.RawData); AsymmetricKeyParameter signingKey = GetPrivateKeyParameter(issuerCertificate); ISignatureFactory signatureFactory = new Asn1SignatureFactory(GetRSAHashAlgorithm(defaultHashSize), signingKey, random); X509V2CrlGenerator crlGen = new X509V2CrlGenerator(); crlGen.SetIssuerDN(bcCertCA.IssuerDN); crlGen.SetThisUpdate(DateTime.UtcNow); crlGen.SetNextUpdate(DateTime.UtcNow.AddMonths(12)); // merge all existing revocation list if (issuerCrls != null) { X509CrlParser parser = new X509CrlParser(); foreach (X509CRL issuerCrl in issuerCrls) { X509Crl crl = parser.ReadCrl(issuerCrl.RawData); crlGen.AddCrl(crl); var crlVersion = GetCrlNumber(crl); if (crlVersion.IntValue > crlSerialNumber.IntValue) { crlSerialNumber = crlVersion; } } } DateTime now = DateTime.UtcNow; if (revokedCertificates == null || revokedCertificates.Count == 0) { // add a dummy revoked cert crlGen.AddCrlEntry(BigInteger.One, now, CrlReason.Unspecified); } else { // add the revoked cert foreach (var revokedCertificate in revokedCertificates) { crlGen.AddCrlEntry(GetSerialNumber(revokedCertificate), now, CrlReason.PrivilegeWithdrawn); } } crlGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(bcCertCA)); // set new serial number crlSerialNumber = crlSerialNumber.Add(BigInteger.One); crlGen.AddExtension(X509Extensions.CrlNumber, false, new CrlNumber(crlSerialNumber)); // generate updated CRL X509Crl updatedCrl = crlGen.Generate(signatureFactory); return(new X509CRL(updatedCrl.GetEncoded())); } }
/// <summary> /// Add update period for the crl to the custom amount of time provided as parameters. /// </summary> /// <param name="validFrom"></param> /// <param name="validTo"></param> /// <returns></returns> public CrlBuilder AddUpdatePeriod(DateTime validFrom, DateTime validTo) { crlGenerator.SetThisUpdate(validFrom); crlGenerator.SetNextUpdate(validTo); return(this); }
/// <summary> /// Revoke the CA signed certificate. /// The issuer CA public key, the private key and the crl reside in the storepath. /// The CRL number is increased by one and existing CRL for the issuer are deleted from the store. /// </summary> public static async Task <X509CRL> RevokeCertificateAsync( string storePath, X509Certificate2 certificate, string issuerKeyFilePassword = null ) { X509CRL updatedCRL = null; try { string subjectName = certificate.IssuerName.Name; string keyId = null; string serialNumber = null; // caller may want to create empty CRL using the CA cert itself bool isCACert = IsCertificateAuthority(certificate); // find the authority key identifier. X509AuthorityKeyIdentifierExtension authority = FindAuthorityKeyIdentifier(certificate); if (authority != null) { keyId = authority.KeyId; serialNumber = authority.SerialNumber; } else { throw new ArgumentException("Certificate does not contain an Authority Key"); } if (!isCACert) { if (serialNumber == certificate.SerialNumber || Utils.CompareDistinguishedName(certificate.Subject, certificate.Issuer)) { throw new ServiceResultException(StatusCodes.BadCertificateInvalid, "Cannot revoke self signed certificates"); } } X509Certificate2 certCA = null; using (ICertificateStore store = CertificateStoreIdentifier.OpenStore(storePath)) { if (store == null) { throw new ArgumentException("Invalid store path/type"); } certCA = await FindIssuerCABySerialNumberAsync(store, certificate.Issuer, serialNumber); if (certCA == null) { throw new ServiceResultException(StatusCodes.BadCertificateInvalid, "Cannot find issuer certificate in store."); } if (!certCA.HasPrivateKey) { throw new ServiceResultException(StatusCodes.BadCertificateInvalid, "Issuer certificate has no private key, cannot revoke certificate."); } CertificateIdentifier certCAIdentifier = new CertificateIdentifier(certCA); certCAIdentifier.StorePath = storePath; certCAIdentifier.StoreType = CertificateStoreIdentifier.DetermineStoreType(storePath); X509Certificate2 certCAWithPrivateKey = await certCAIdentifier.LoadPrivateKey(issuerKeyFilePassword); if (certCAWithPrivateKey == null) { throw new ServiceResultException(StatusCodes.BadCertificateInvalid, "Failed to load issuer private key. Is the password correct?"); } List <X509CRL> certCACrl = store.EnumerateCRLs(certCA, false); using (var cfrg = new CertificateFactoryRandomGenerator()) { // cert generators SecureRandom random = new SecureRandom(cfrg); BigInteger crlSerialNumber = BigInteger.Zero; Org.BouncyCastle.X509.X509Certificate bcCertCA = new X509CertificateParser().ReadCertificate(certCA.RawData); AsymmetricKeyParameter signingKey = GetPrivateKeyParameter(certCAWithPrivateKey); ISignatureFactory signatureFactory = new Asn1SignatureFactory(GetRSAHashAlgorithm(defaultHashSize), signingKey, random); X509V2CrlGenerator crlGen = new X509V2CrlGenerator(); crlGen.SetIssuerDN(bcCertCA.IssuerDN); crlGen.SetThisUpdate(DateTime.UtcNow); crlGen.SetNextUpdate(DateTime.UtcNow.AddMonths(12)); // merge all existing revocation list X509CrlParser parser = new X509CrlParser(); foreach (X509CRL caCrl in certCACrl) { X509Crl crl = parser.ReadCrl(caCrl.RawData); crlGen.AddCrl(crl); var crlVersion = GetCrlNumber(crl); if (crlVersion.IntValue > crlSerialNumber.IntValue) { crlSerialNumber = crlVersion; } } if (isCACert) { // add a dummy revoked cert crlGen.AddCrlEntry(BigInteger.One, DateTime.UtcNow, CrlReason.Superseded); } else { // add the revoked cert crlGen.AddCrlEntry(GetSerialNumber(certificate), DateTime.UtcNow, CrlReason.PrivilegeWithdrawn); } crlGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(bcCertCA)); // set new serial number crlSerialNumber = crlSerialNumber.Add(BigInteger.One); crlGen.AddExtension(X509Extensions.CrlNumber, false, new CrlNumber(crlSerialNumber)); // generate updated CRL X509Crl updatedCrl = crlGen.Generate(signatureFactory); // add updated CRL to store updatedCRL = new X509CRL(updatedCrl.GetEncoded()); store.AddCRL(updatedCRL); // delete outdated CRLs from store foreach (X509CRL caCrl in certCACrl) { store.DeleteCRL(caCrl); } } store.Close(); } } catch (Exception e) { throw e; } return(updatedCRL); }
public override void SetThisUpdate(DateTime date) { m_Generator.SetThisUpdate(date); }
/// <inheritdoc/> public Task <Crl> CreateCrlAsync(Certificate issuer, SignatureType signature, IEnumerable <Certificate> revokedCertificates, DateTime?nextUpdate, CancellationToken ct) { try { if (issuer == null) { throw new ArgumentNullException(nameof(issuer)); } if (issuer.RawData == null) { throw new ArgumentNullException(nameof(issuer.RawData)); } if (issuer.IssuerPolicies == null) { throw new ArgumentNullException(nameof(issuer.IssuerPolicies)); } if (issuer.KeyHandle == null) { throw new ArgumentNullException(nameof(issuer.KeyHandle)); } var bcCertCA = new X509CertificateParser().ReadCertificate(issuer.RawData); var thisUpdate = DateTime.UtcNow; var crlGen = new X509V2CrlGenerator(); crlGen.SetIssuerDN(bcCertCA.SubjectDN); crlGen.SetThisUpdate(DateTime.UtcNow); crlGen.SetNextUpdate(nextUpdate ?? issuer.NotAfterUtc); if (revokedCertificates == null || !revokedCertificates.Any()) { // add a dummy entry crlGen.AddCrlEntry(BigInteger.One, thisUpdate, CrlReason.Unspecified); } else { // add the revoked certs foreach (var revokedCertificate in revokedCertificates) { var revoked = revokedCertificate.Revoked?.Date ?? thisUpdate; crlGen.AddCrlEntry(new BigInteger(1, revokedCertificate.SerialNumber), revoked, CrlReason.PrivilegeWithdrawn); } } crlGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(bcCertCA)); // set new serial number var crlSerialNumber = BigInteger.ValueOf(DateTime.UtcNow.ToFileTimeUtc()); crlGen.AddExtension(X509Extensions.CrlNumber, false, new CrlNumber(crlSerialNumber)); // generate updated CRL var signatureGenerator = _signer.CreateX509SignatureGenerator( issuer.KeyHandle, signature); var signatureFactory = new SignatureFactory(signature, signatureGenerator); var updatedCrl = crlGen.Generate(signatureFactory); return(Task.FromResult(CrlEx.ToCrl(updatedCrl.GetEncoded()))); } catch (Exception ex) { return(Task.FromException <Crl>(ex)); } }