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); }
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 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 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> /// Issue a CRL (containing all revoked certificates) /// </summary> /// <returns></returns> public virtual string IssueCRL() { X509V2CrlGenerator crlGen = new X509V2CrlGenerator(); // Generate CRL try { createCRL(crlGen); X509Crl crl = crlGen.Generate(privateKey); // Write CRL to file File.WriteAllBytes(crlFileLocation, crl.GetEncoded()); logEvent(LogEvent.EventType.IssueCert, "CRL Published. Serial: " + lastCRL); } catch (Exception ex) { LogEvent.WriteEvent(eventLog, LogEvent.EventType.Error, "Failed CRL issue: " + ex.Message); throw new ApplicationException("Failed CRL Issue", ex); } return(lastCRL); }
/// <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); }
public override CertificateRevocationListBase Generate(RSAKeyPair keyPair) { var r = m_Generator.Generate(PrivateKeyFactory.CreateKey(keyPair.PrivateKey)); return(new CertificateRevocationListBC(new MemoryStream(r.GetEncoded()))); }
/// <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)); } }
/// <summary> /// Creates a crl based on the build chain constructed. /// </summary> /// <param name="issuerPrivateKey"></param> /// <returns></returns> public X509Crl Generate(AsymmetricKeyParameter issuerPrivateKey) { return(crlGenerator.Generate(new Asn1SignatureFactory(signatureAlgorithm, issuerPrivateKey, secureRandom))); }
/// <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); }
/// <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())); } }
protected override X509Crl GenerateCrl(AsymmetricKeyParameter privateKey, X509V2CrlGenerator crlGen) { crlGen.SetSignatureAlgorithm("SHA1withRSA"); return(crlGen.Generate(privateKey)); }
protected override X509Crl GenerateCrl(AsymmetricKeyParameter privateKey, X509V2CrlGenerator crlGen) { var signer = new GostSignerFactory(privateKey); return(crlGen.Generate(signer)); }