use of org.bouncycastle.asn1.x509.Time in project keycloak by keycloak.
the class CRLUtils method check.
/**
* Check the signature on CRL and check if 1st certificate from the chain ((The actual certificate from the client)) is valid and not available on CRL.
*
* @param certs The 1st certificate is the actual certificate of the user. The other certificates represents the certificate chain
* @param crl Given CRL
* @throws GeneralSecurityException if some error in validation happens. Typically certificate not valid, or CRL signature not valid
*/
public static void check(X509Certificate[] certs, X509CRL crl, KeycloakSession session) throws GeneralSecurityException {
if (certs.length < 2) {
throw new GeneralSecurityException("Not possible to verify signature on CRL. X509 certificate doesn't have CA chain available on it");
}
X500Principal crlIssuerPrincipal = crl.getIssuerX500Principal();
X509Certificate crlSignatureCertificate = null;
// Try to find the certificate in the CA chain, which was used to sign the CRL
for (int i = 1; i < certs.length; i++) {
X509Certificate currentCACert = certs[i];
if (crlIssuerPrincipal.equals(currentCACert.getSubjectX500Principal())) {
crlSignatureCertificate = currentCACert;
log.tracef("Found certificate used to sign CRL in the CA chain of the certificate. CRL issuer: %s", crlIssuerPrincipal);
break;
}
}
// Try to find the CRL issuer certificate in the truststore
if (crlSignatureCertificate == null) {
log.tracef("Not found CRL issuer '%s' in the CA chain of the certificate. Fallback to lookup CRL issuer in the truststore", crlIssuerPrincipal);
crlSignatureCertificate = findCRLSignatureCertificateInTruststore(session, certs, crlIssuerPrincipal);
}
// Verify signature on CRL
// TODO: It will be nice to cache CRLs and also verify their signatures just once at the time when CRL is loaded, rather than in every request
crl.verify(crlSignatureCertificate.getPublicKey());
// Finally check if
if (crl.isRevoked(certs[0])) {
String message = String.format("Certificate has been revoked, certificate's subject: %s", certs[0].getSubjectDN().getName());
log.debug(message);
throw new GeneralSecurityException(message);
}
}
use of org.bouncycastle.asn1.x509.Time in project keystore-explorer by kaikramer.
the class JarSigner method createSignatureBlock.
private static byte[] createSignatureBlock(byte[] toSign, PrivateKey privateKey, X509Certificate[] certificateChain, SignatureType signatureType, String tsaUrl, Provider provider) throws CryptoException {
try {
List<X509Certificate> certList = new ArrayList<>();
Collections.addAll(certList, certificateChain);
DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build();
JcaContentSignerBuilder csb = new JcaContentSignerBuilder(signatureType.jce()).setSecureRandom(SecureRandom.getInstance("SHA1PRNG"));
if (provider != null) {
csb.setProvider(provider);
}
JcaSignerInfoGeneratorBuilder siGeneratorBuilder = new JcaSignerInfoGeneratorBuilder(digCalcProv);
// remove cmsAlgorithmProtect for compatibility reasons
SignerInfoGenerator sigGen = siGeneratorBuilder.build(csb.build(privateKey), certificateChain[0]);
final CMSAttributeTableGenerator sAttrGen = sigGen.getSignedAttributeTableGenerator();
sigGen = new SignerInfoGenerator(sigGen, new DefaultSignedAttributeTableGenerator() {
@Override
public AttributeTable getAttributes(@SuppressWarnings("rawtypes") Map parameters) {
AttributeTable ret = sAttrGen.getAttributes(parameters);
return ret.remove(CMSAttributes.cmsAlgorithmProtect);
}
}, sigGen.getUnsignedAttributeTableGenerator());
CMSSignedDataGenerator dataGen = new CMSSignedDataGenerator();
dataGen.addSignerInfoGenerator(sigGen);
dataGen.addCertificates(new JcaCertStore(certList));
CMSSignedData signedData = dataGen.generate(new CMSProcessableByteArray(toSign), true);
// now let TSA time-stamp the signature
if (tsaUrl != null && !tsaUrl.isEmpty()) {
signedData = addTimestamp(tsaUrl, signedData);
}
return signedData.getEncoded();
} catch (Exception ex) {
throw new CryptoException(res.getString("SignatureBlockCreationFailed.exception.message"), ex);
}
}
use of org.bouncycastle.asn1.x509.Time in project keystore-explorer by kaikramer.
the class Asn1Dump method dumpGeneralizedTime.
private String dumpGeneralizedTime(ASN1GeneralizedTime asn1Time) {
StringBuilder sb = new StringBuilder();
sb.append(indentSequence.toString(indentLevel));
sb.append("GENERALIZED TIME=");
Date date;
try {
date = asn1Time.getDate();
} catch (ParseException e) {
throw new RuntimeException("Cannot parse generalized time");
}
String formattedDate = new SimpleDateFormat("dd/MMM/yyyy HH:mm:ss.SSS z").format(date);
sb.append(formattedDate);
sb.append(" (");
sb.append(asn1Time.getTime());
sb.append(")");
sb.append(NEWLINE);
return sb.toString();
}
use of org.bouncycastle.asn1.x509.Time in project keystore-explorer by kaikramer.
the class Asn1Dump method dumpUTCTime.
private String dumpUTCTime(ASN1UTCTime asn1Time) {
StringBuilder sb = new StringBuilder();
sb.append(indentSequence.toString(indentLevel));
sb.append("UTC TIME=");
// UTCTime, note does not support ms precision hence the different date format
Date date;
try {
date = asn1Time.getDate();
} catch (ParseException e) {
throw new RuntimeException("Cannot parse utc time");
}
String formattedDate = new SimpleDateFormat("dd/MMM/yyyy HH:mm:ss z").format(date);
sb.append(formattedDate);
sb.append(" (");
sb.append(asn1Time.getTime());
sb.append(")");
sb.append(NEWLINE);
return sb.toString();
}
use of org.bouncycastle.asn1.x509.Time in project Spark by igniterealtime.
the class SparkTrustManager method validatePath.
/**
* Validate certificate path
*
* @throws NoSuchAlgorithmException
* @throws KeyStoreException
* @throws InvalidAlgorithmParameterException
* @throws CertPathValidatorException
* @throws CertPathBuilderException
* @throws CertificateException
*/
private void validatePath(X509Certificate[] chain) throws NoSuchAlgorithmException, KeyStoreException, InvalidAlgorithmParameterException, CertPathValidatorException, CertPathBuilderException, CertificateException {
// PKIX algorithm is defined in rfc3280
CertPathValidator certPathValidator = CertPathValidator.getInstance("PKIX");
CertPathBuilder certPathBuilder = CertPathBuilder.getInstance("PKIX");
X509CertSelector certSelector = new X509CertSelector();
// set last certificate (often root CA) from chain for CertSelector so trust store must contain it
certSelector.setCertificate(chain[chain.length - 1]);
// checks against time validity aren't done here as are already done in checkDateValidity (X509Certificate[]
// chain)
certSelector.setCertificateValid(null);
// create parameters using trustStore as source of Trust Anchors and using X509CertSelector
PKIXBuilderParameters parameters = new PKIXBuilderParameters(allStore, certSelector);
// will use PKIXRevocationChecker (or nothing if revocation mechanisms are
// disabled) instead of the default revocation checker
parameters.setRevocationEnabled(false);
// certificates from blacklist will be rejected
if (acceptRevoked == false) {
// OCSP checking is done according to Java PKI Programmer's Guide, PKIXRevocationChecker was added in Java 8:
// https://docs.oracle.com/javase/8/docs/technotes/guides/security/certpath/CertPathProgGuide.html#PKIXRevocationChecker
PKIXRevocationChecker checker = (PKIXRevocationChecker) certPathBuilder.getRevocationChecker();
EnumSet<PKIXRevocationChecker.Option> checkerOptions = EnumSet.noneOf(PKIXRevocationChecker.Option.class);
// is enabled then in case of network issues revocation checking is omitted
if (allowSoftFail) {
checkerOptions.add(PKIXRevocationChecker.Option.SOFT_FAIL);
}
// check OCSP, CRL serve as backup
if (checkOCSP && checkCRL) {
checker.setOptions(checkerOptions);
parameters.addCertPathChecker(checker);
} else if (!checkOCSP && checkCRL) {
// check only CRL, if CRL fail then there is no fallback to OCSP
checkerOptions.add(PKIXRevocationChecker.Option.PREFER_CRLS);
checkerOptions.add(PKIXRevocationChecker.Option.NO_FALLBACK);
checker.setOptions(checkerOptions);
parameters.addCertPathChecker(checker);
}
}
try {
CertPathBuilderResult pathResult = certPathBuilder.build(parameters);
CertPath certPath = pathResult.getCertPath();
PKIXCertPathValidatorResult validationResult = (PKIXCertPathValidatorResult) certPathValidator.validate(certPath, parameters);
X509Certificate trustedCert = validationResult.getTrustAnchor().getTrustedCert();
if (trustedCert == null) {
throw new CertificateException("certificate path failed: Trusted CA is NULL");
}
// this extension is last certificate: root CA
for (int i = 0; i < chain.length - 1; i++) {
checkBasicConstraints(chain[i]);
}
} catch (CertificateRevokedException e) {
Log.warning("Certificate was revoked", e);
for (X509Certificate cert : chain) {
for (X509CRL crl : crlCollection) {
if (crl.isRevoked(cert)) {
try {
addToBlackList(cert);
} catch (IOException | HeadlessException | InvalidNameException e1) {
Log.error("Couldn't move to the blacklist", e1);
}
break;
}
}
}
throw new CertificateException("Certificate was revoked");
}
}
Aggregations