List of usage examples for java.security.cert CRLException getMessage
public String getMessage()
From source file:be.fedict.eid.dss.spi.utils.XAdESUtils.java
public static void checkReference(X509CRL crl, CompleteRevocationRefsType completeRevocationRefs) throws XAdESValidationException { byte[] encodedCRL; try {/*from w w w . j av a2 s .com*/ encodedCRL = crl.getEncoded(); } catch (CRLException e) { throw new XAdESValidationException("CRL encoding error: " + e.getMessage(), e); } CRLRefsType crlRefs = completeRevocationRefs.getCRLRefs(); if (null == crlRefs) { throw new XAdESValidationException("missing CRLRefs"); } for (CRLRefType crlRef : crlRefs.getCRLRef()) { DigestAlgAndValueType digestAlgAndValue = crlRef.getDigestAlgAndValue(); String xmlDigestAlgo = digestAlgAndValue.getDigestMethod().getAlgorithm(); MessageDigest messageDigest; try { messageDigest = MessageDigest.getInstance(getDigestAlgo(xmlDigestAlgo)); } catch (NoSuchAlgorithmException e) { throw new XAdESValidationException("message digest algo error: " + e.getMessage(), e); } byte[] expectedDigestValue = messageDigest.digest(encodedCRL); byte[] refDigestValue = digestAlgAndValue.getDigestValue(); if (Arrays.equals(expectedDigestValue, refDigestValue)) { return; } } throw new XAdESValidationException("CRL not referenced"); }
From source file:be.fedict.trust.crl.OnlineCrlRepository.java
public X509CRL findCrl(URI crlUri, X509Certificate issuerCertificate, Date validationDate) { try {/*from w w w . j a v a2 s . c om*/ return getCrl(crlUri); } catch (CRLException e) { LOG.debug("error parsing CRL: " + e.getMessage(), e); return null; } catch (Exception e) { LOG.error("find CRL error: " + e.getMessage(), e); return null; } }
From source file:be.fedict.trust.crl.CrlTrustLinker.java
private TrustLinkerResult processCrl(URI crlUri, X509Certificate childCertificate, X509Certificate certificate, Date validationDate, RevocationData revocationData, BigInteger baseCrlNumber) { LOG.debug("CRL URI: " + crlUri); X509CRL x509crl = this.crlRepository.findCrl(crlUri, certificate, validationDate); if (null == x509crl) { return null; }// w ww . j a va 2s.com // check CRL integrity boolean crlIntegrityResult = checkCrlIntegrity(x509crl, certificate, validationDate); if (false == crlIntegrityResult) { return null; } // check CRL signature TrustLinkerResult trustResult = TrustValidator.checkSignatureAlgorithm(x509crl.getSigAlgName()); if (!trustResult.isValid()) { return trustResult; } // we don't support indirect CRLs if (isIndirectCRL(x509crl)) { LOG.debug("indirect CRL detected"); return null; } LOG.debug("CRL number: " + getCrlNumber(x509crl)); // check delta CRL indicator against completeCrlNuber if (null != baseCrlNumber) { BigInteger crlNumber = getDeltaCrlIndicator(x509crl); if (!baseCrlNumber.equals(crlNumber)) { LOG.error("Delta CRL indicator (" + crlNumber + ") not equals base CRL number(" + baseCrlNumber + ")"); return null; } } // fill up revocation data if not null with this valid CRL if (null != revocationData) { try { revocationData.getCrlRevocationData().add(new CRLRevocationData(x509crl.getEncoded())); } catch (CRLException e) { LOG.error("CRLException: " + e.getMessage(), e); throw new RuntimeException("CRLException : " + e.getMessage(), e); } } boolean revoked = true; X509CRLEntry crlEntry = x509crl.getRevokedCertificate(childCertificate.getSerialNumber()); if (null == crlEntry) { LOG.debug("CRL OK for: " + childCertificate.getSubjectX500Principal()); revoked = false; } else if (crlEntry.getRevocationDate().after(validationDate)) { LOG.debug("CRL OK for: " + childCertificate.getSubjectX500Principal() + " at " + validationDate); revoked = false; } if (null != x509crl.getExtensionValue(X509Extensions.DeltaCRLIndicator.getId())) { // Delta CRL if (!revoked) return null; } else { // Base CRL, look for delta's List<URI> deltaCrlUris = getDeltaCrlUris(x509crl); if (null != deltaCrlUris) { for (URI deltaCrlUri : deltaCrlUris) { LOG.debug("delta CRL: " + deltaCrlUri.toString()); TrustLinkerResult result = processCrl(deltaCrlUri, childCertificate, certificate, validationDate, revocationData, getCrlNumber(x509crl)); if (null != result) return result; } } } if (!revoked) return new TrustLinkerResult(true); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_REVOCATION_STATUS, "certificate revoked by CRL=" + crlEntry.getSerialNumber()); }
From source file:at.gv.egiz.pdfas.lib.pki.impl.DefaultCertificateVerificationDataProvider.java
@Override public CertificateVerificationData getCertificateVerificationData( java.security.cert.X509Certificate eeCertificate, ISettings settings) throws CertificateException, IOException { X509Certificate iaikEeCertificate = toIAIKX509Certificate(Objects.requireNonNull(eeCertificate)); // @formatter:off final Set<java.security.cert.X509Certificate> certs = new LinkedHashSet<>(); // not thread-safe final List<byte[]> ocsps = new ArrayList<>(); // not thread-safe final Set<java.security.cert.X509CRL> crls = new LinkedHashSet<>(); // not thread-safe // @formatter:on StopWatch sw = new StopWatch(); sw.start();// w ww . ja v a 2s.c o m if (log.isDebugEnabled()) { log.debug("Retrieving certificate validation info info for {}", iaikEeCertificate.getSubjectDN()); } else if (log.isInfoEnabled()) { log.info("Retrieving certificate validation data for certificate (SHA-1 fingerprint): {}", Hex.encodeHexString(iaikEeCertificate.getFingerprintSHA())); } // retrieve certificate chain for eeCertificate X509Certificate[] caChainCertificates = retrieveChain(iaikEeCertificate, Objects.requireNonNull(settings)); // build up full (sorted) chain including eeCertificate X509Certificate[] fullChainCertificates = Util.createCertificateChain(iaikEeCertificate, caChainCertificates); // add chain to certs list certs.addAll(Arrays.asList(fullChainCertificates)); // determine revocation info, preferring OCSP // assume last certificate in chain is trust anchor OCSPClient ocspClient = OCSPClient.builder().setConnectTimeOutMillis(DEFAULT_CONNECTION_TIMEOUT_MS) .setSocketTimeOutMillis(DEFAULT_READ_TIMEOUT_MS).build(); for (int i = 0; i < fullChainCertificates.length - 1; i++) { final X509Certificate subjectCertificate = fullChainCertificates[i]; final X509Certificate issuerCertificate = fullChainCertificates[i + 1]; OCSPResponse ocspResponse = null; if (OCSPClient.Util.hasOcspResponder(subjectCertificate)) { try { ocspResponse = ocspClient.getOcspResponse(issuerCertificate, subjectCertificate); } catch (Exception e) { log.info("Unable to retrieve OCSP response: {}", String.valueOf(e)); } } if (ocspResponse != null) { ocsps.add(ocspResponse.getEncoded()); // add ocsp signer certificate to certs // The currently used OCSP client support BasicOCSPResponse only, otherwise an exception would have been // thrown earlier. Therefore we can safely cast to BasicOCSPResponse here. X509Certificate ocspSignerCertificate = ((BasicOCSPResponse) ocspResponse.getResponse()) .getSignerCertificate(); certs.add(ocspSignerCertificate); } else { // fall back to CRL CRLDistributionPoints cRLDistributionPoints; try { cRLDistributionPoints = (CRLDistributionPoints) subjectCertificate .getExtension(CRLDistributionPoints.oid); } catch (X509ExtensionInitException e) { throw new IllegalStateException("Unable to initialize extension CRLDistributionPoints.", e); } X509CRL x509Crl = null; if (cRLDistributionPoints != null) { if (log.isDebugEnabled()) { log.debug("Retrieving CRL revocation info for: {}", subjectCertificate.getSubjectDN()); } else if (log.isInfoEnabled()) { log.info("Retrieving CRL revocation info for certificate (SHA-1 fingerprint): {}", Hex.encodeHexString(subjectCertificate.getFingerprintSHA())); } Exception lastException = null; @SuppressWarnings("unchecked") Enumeration<DistributionPoint> e = cRLDistributionPoints.getDistributionPoints(); while (e.hasMoreElements() && x509Crl == null) { DistributionPoint distributionPoint = e.nextElement(); // inspect distribution point if (distributionPoint.containsUriDpName()) { String[] distributionPointNameURIs = distributionPoint.getDistributionPointNameURIs(); for (String distributionPointNameURI : distributionPointNameURIs) { URL url; try { log.debug("Trying to download crl from distribution point: {}", distributionPointNameURI); if (distributionPointNameURI.toLowerCase().startsWith("ldap://")) { url = new URL(null, distributionPointNameURI, new iaik.x509.net.ldap.Handler()); } else { url = new URL(distributionPointNameURI); } URLConnection urlConnection = url.openConnection(); urlConnection.setConnectTimeout(DEFAULT_CONNECTION_TIMEOUT_MS); urlConnection.setReadTimeout(DEFAULT_READ_TIMEOUT_MS); try (InputStream in = urlConnection.getInputStream()) { x509Crl = new X509CRL(in); // we got crl, exit loop break; } catch (CRLException e1) { lastException = e1; log.debug("Unable to parse CRL read from distribution point: {} ({})", distributionPointNameURI, e1.getMessage()); } } catch (MalformedURLException e1) { log.debug("Unsupported CRL distribution point uri: {} ({})", distributionPointNameURI, e1.getMessage()); lastException = e1; } catch (IOException e1) { log.debug("Error reading from CRL distribution point uri: {} ({})", distributionPointNameURI, e1.getMessage()); lastException = e1; } catch (Exception e1) { log.debug("Unknown error reading from CRL distribution point uri: {} ({})", distributionPointNameURI, e1.getMessage()); lastException = e1; } } } } if (x509Crl != null) { crls.add(x509Crl); } else if (lastException != null) { log.info("Unable to load CRL: {}", String.valueOf(lastException)); } } } } sw.stop(); log.debug("Querying certificate validation info took: {}ms", sw.getTime()); return new CertificateVerificationData() { @Override public List<byte[]> getEncodedOCSPResponses() { return ocsps; } @Override public Set<java.security.cert.X509Certificate> getChainCerts() { return certs; } @Override public Set<java.security.cert.X509CRL> getCRLs() { return crls; } }; }
From source file:mitm.common.security.crl.CRLStoreUpdaterImpl.java
private int downloadCRLs(Set<URI> uris) { int crlsAdded = 0; for (URI uri : uris) { if (uri == null) { logger.warn("URL is null."); continue; }/*from w ww .ja va 2 s .c o m*/ if (uri.getScheme() == null) { logger.warn("Missing scheme. " + uri); } logger.debug("Downloading CRL from: " + uri); try { Collection<? extends CRL> downloadedCrls = updaterParameters.getCRLDownloader().downloadCRLs(uri); logger.debug("Successfully downloaded CRLs from: " + uri); int newAdded = updaterParameters.getCRLStoreMaintainer().addCRLs(downloadedCrls); crlsAdded = crlsAdded + newAdded; } catch (CRLException e) { logger.error("Error handling CRL. URI: " + uri, e); } catch (IOException e) { /* * We will log WARN level because downloading CRLs often result in IOException's because the CRL * distribution point is no longer available for a lot of roots. */ logger.warn("IO Exception downloading CRL. URI: " + uri + ". Message: " + e.getMessage()); if (logger.isDebugEnabled()) { logger.debug("More info.", e); } } catch (Exception e) { /* * Catch all exceptions to make sure that other CRLs are downloaded. */ logger.error("Error while downloading CRL. URI: " + uri, e); } } return crlsAdded; }
From source file:net.maritimecloud.identityregistry.utils.CertificateUtil.java
/** * Creates a Certificate Revocation List (CRL) for the certificate serialnumbers given. * * @param revokedCerts List of the serialnumbers that should be revoked. *///ww w. j a va2 s. co m public void generateRootCACRL(String signName, List<net.maritimecloud.identityregistry.model.database.Certificate> revokedCerts, PrivateKeyEntry keyEntry, String outputCaCrlPath) { Date now = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(now); cal.add(Calendar.YEAR, 1); X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(new X500Name(signName), now); crlBuilder.setNextUpdate(cal.getTime()); // The next CRL is next year (dummy value) if (revokedCerts != null) { for (net.maritimecloud.identityregistry.model.database.Certificate cert : revokedCerts) { String certReason = cert.getRevokeReason().toLowerCase(); int reason = getCRLReasonFromString(certReason); crlBuilder.addCRLEntry(cert.getSerialNumber(), cert.getRevokedAt(), reason); } } //crlBuilder.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); //crlBuilder.addExtension(X509Extensions.CRLNumber, false, new CRLNumber(BigInteger.valueOf(1))); JcaContentSignerBuilder signBuilder = new JcaContentSignerBuilder(SIGNER_ALGORITHM); signBuilder.setProvider(BC_PROVIDER_NAME); ContentSigner signer; try { signer = signBuilder.build(keyEntry.getPrivateKey()); } catch (OperatorCreationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); return; } X509CRLHolder cRLHolder = crlBuilder.build(signer); JcaX509CRLConverter converter = new JcaX509CRLConverter(); converter.setProvider(BC_PROVIDER_NAME); X509CRL crl; try { crl = converter.getCRL(cRLHolder); } catch (CRLException e) { throw new RuntimeException(e.getMessage(), e); } String pemCrl; try { pemCrl = CertificateUtil.getPemFromEncoded("X509 CRL", crl.getEncoded()); } catch (CRLException e) { log.warn("unable to generate RootCACRL", e); return; } try { BufferedWriter writer = new BufferedWriter(new FileWriter(outputCaCrlPath)); writer.write(pemCrl); writer.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.netscape.ca.CertificateAuthority.java
/** * Signs CRL using the specified signature algorithm. * If no algorithm is specified the CA's default signing algorithm * is used./*ww w .j ava2 s. c om*/ * <P> * * @param crl the CRL to be signed. * @param algname the algorithm name to use. This is a JCA name such * as MD5withRSA, etc. If set to null the default signing algorithm * is used. * * @return the signed CRL */ public X509CRLImpl sign(X509CRLImpl crl, String algname) throws EBaseException { ensureReady(); X509CRLImpl signedcrl = null; IStatsSubsystem statsSub = (IStatsSubsystem) CMS.getSubsystem("stats"); if (statsSub != null) { statsSub.startTiming("signing"); } try (DerOutputStream out = new DerOutputStream()) { DerOutputStream tmp = new DerOutputStream(); if (algname == null) { algname = mSigningUnit.getDefaultAlgorithm(); } crl.encodeInfo(tmp); AlgorithmId.get(algname).encode(tmp); byte[] tbsCertList = crl.getTBSCertList(); byte[] signature = mCRLSigningUnit.sign(tbsCertList, algname); if (crl.setSignature(signature)) { tmp.putBitString(signature); out.write(DerValue.tag_Sequence, tmp); if (crl.setSignedCRL(out.toByteArray())) { signedcrl = crl; // signedcrl = new X509CRLImpl(out.toByteArray()); } else { logger.warn("Failed to add signed-CRL to CRL object."); } } else { logger.warn("Failed to add signature to CRL object."); } } catch (CRLException e) { log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_SIGN_CRL", e.toString(), e.getMessage())); throw new ECAException(CMS.getUserMessage("CMS_CA_SIGNING_CRL_FAILED", e.getMessage())); } catch (X509ExtensionException e) { log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_SIGN_CRL", e.toString(), e.getMessage())); throw new ECAException(CMS.getUserMessage("CMS_CA_SIGNING_CRL_FAILED", e.getMessage())); } catch (NoSuchAlgorithmException e) { log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_SIGN_CRL", e.toString(), e.getMessage())); throw new ECAException(CMS.getUserMessage("CMS_CA_SIGNING_CRL_FAILED", e.getMessage())); } catch (IOException e) { log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_SIGN_CRL", e.toString(), e.getMessage())); throw new ECAException(CMS.getUserMessage("CMS_CA_SIGNING_CRL_FAILED", e.getMessage())); } finally { if (statsSub != null) { statsSub.endTiming("signing"); } } return signedcrl; }