List of usage examples for java.security.cert X509CRL verify
public abstract void verify(PublicKey key) throws CRLException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException;
From source file:be.fedict.trust.crl.CrlTrustLinker.java
/** * Checks the integrity of the given X509 CRL. * // ww w.j a v a2s.co m * @param x509crl * the X509 CRL to verify the integrity. * @param issuerCertificate * the assumed issuer of the given X509 CRL. * @param validationDate * the validate date. * @return <code>true</code> if integrity is OK, <code>false</code> * otherwise. */ public static boolean checkCrlIntegrity(X509CRL x509crl, X509Certificate issuerCertificate, Date validationDate) { if (false == x509crl.getIssuerX500Principal().equals(issuerCertificate.getSubjectX500Principal())) { return false; } try { x509crl.verify(issuerCertificate.getPublicKey()); } catch (Exception e) { return false; } Date thisUpdate = x509crl.getThisUpdate(); LOG.debug("validation date: " + validationDate); LOG.debug("CRL this update: " + thisUpdate); if (thisUpdate.after(validationDate)) { LOG.warn("CRL too young"); return false; } LOG.debug("CRL next update: " + x509crl.getNextUpdate()); if (validationDate.after(x509crl.getNextUpdate())) { LOG.debug("CRL too old"); return false; } // assert cRLSign KeyUsage bit if (null == issuerCertificate.getKeyUsage()) { LOG.debug("No KeyUsage extension for CRL issuing certificate"); return false; } if (false == issuerCertificate.getKeyUsage()[6]) { LOG.debug("cRLSign bit not set for CRL issuing certificate"); return false; } return true; }
From source file:dk.itst.oiosaml.sp.metadata.CRLChecker.java
private boolean checkCRLSignature(X509CRL crl, X509Certificate certificate, Configuration conf) { if (conf.getString(Constants.PROP_CRL_TRUSTSTORE, null) == null) return true; CredentialRepository cr = new CredentialRepository(); String location = SAMLConfiguration.getStringPrefixedWithBRSHome(conf, Constants.PROP_CRL_TRUSTSTORE); cr.getCertificate(location, conf.getString(Constants.PROP_CRL_TRUSTSTORE_PASSWORD), null); for (X509Credential cred : cr.getCredentials()) { try {//from w ww.ja v a2 s. com crl.verify(cred.getPublicKey()); return true; } catch (Exception e) { log.debug("CRL not signed by " + cred); } } return false; }
From source file:be.fedict.trust.service.bean.DownloaderMDB.java
private void processColdStartMessage(ColdStartMessage coldStartMessage) { if (null == coldStartMessage) { return;// w ww. j a va 2 s . co m } String crlUrl = coldStartMessage.getCrlUrl(); String certUrl = coldStartMessage.getCertUrl(); LOG.debug("cold start CRL URL: " + crlUrl); LOG.debug("cold start CA URL: " + certUrl); File crlFile = download(crlUrl); File certFile = download(certUrl); // parsing CertificateFactory certificateFactory; try { certificateFactory = CertificateFactory.getInstance("X.509"); } catch (CertificateException e) { LOG.debug("certificate factory error: " + e.getMessage(), e); crlFile.delete(); certFile.delete(); return; } X509Certificate certificate = null; try { certificate = (X509Certificate) certificateFactory.generateCertificate(new FileInputStream(certFile)); } catch (Exception e) { LOG.debug("error DER-parsing certificate"); try { PEMReader pemReader = new PEMReader(new FileReader(certFile)); certificate = (X509Certificate) pemReader.readObject(); pemReader.close(); } catch (Exception e2) { retry("error PEM-parsing certificate", e, certFile, crlFile); } } certFile.delete(); X509CRL crl = null; try { crl = (X509CRL) certificateFactory.generateCRL(new FileInputStream(crlFile)); } catch (Exception e) { retry("error parsing CRL", e, crlFile); } // first check whether the two correspond try { crl.verify(certificate.getPublicKey()); } catch (Exception e) { LOG.error("no correspondence between CRL and CA"); LOG.error("CRL issuer: " + crl.getIssuerX500Principal()); LOG.debug("CA subject: " + certificate.getSubjectX500Principal()); crlFile.delete(); return; } LOG.debug("CRL matches CA: " + certificate.getSubjectX500Principal()); // skip expired CAs Date now = new Date(); Date notAfter = certificate.getNotAfter(); if (now.after(notAfter)) { LOG.warn("CA already expired: " + certificate.getSubjectX500Principal()); crlFile.delete(); return; } // create database entitities CertificateAuthorityEntity certificateAuthority = this.certificateAuthorityDAO .findCertificateAuthority(certificate); if (null != certificateAuthority) { LOG.debug("CA already in cache: " + certificate.getSubjectX500Principal()); crlFile.delete(); return; } /* * Lookup Root CA's trust point via parent certificates' CA entity. */ LOG.debug( "Lookup Root CA's trust point via parent certificates' CA entity - Don't have Issuer's Serial Number??"); String parentIssuerName = certificate.getIssuerX500Principal().toString(); CertificateAuthorityEntity parentCertificateAuthority = this.certificateAuthorityDAO .findCertificateAuthority(parentIssuerName); if (null == parentCertificateAuthority) { LOG.error("CA not found for " + parentIssuerName + " ?!"); crlFile.delete(); return; } LOG.debug("parent CA: " + parentCertificateAuthority.getName()); TrustPointEntity parentTrustPoint = parentCertificateAuthority.getTrustPoint(); if (null != parentTrustPoint) { LOG.debug("trust point parent: " + parentTrustPoint.getName()); LOG.debug("previous trust point fire data: " + parentTrustPoint.getFireDate()); } else { LOG.debug("no parent trust point"); } // create new CA certificateAuthority = this.certificateAuthorityDAO.addCertificateAuthority(certificate, crlUrl); // prepare harvesting certificateAuthority.setTrustPoint(parentTrustPoint); certificateAuthority.setStatus(Status.PROCESSING); if (null != certificateAuthority.getTrustPoint() && null == certificateAuthority.getTrustPoint().getFireDate()) { try { this.schedulingService.startTimer(certificateAuthority.getTrustPoint()); } catch (InvalidCronExpressionException e) { LOG.error("invalid cron expression"); crlFile.delete(); return; } } // notify harvester String crlFilePath = crlFile.getAbsolutePath(); try { this.notificationService.notifyHarvester(certificate.getSubjectX500Principal().toString(), crlFilePath, false); } catch (JMSException e) { crlFile.delete(); throw new RuntimeException(e); } }
From source file:eu.europa.ec.markt.dss.validation.crl.OnlineCRLSource.java
@Override public X509CRL findCrl(final X509Certificate cert, final X509Certificate issuerCert) throws DSSException { final String crlURL = getCrlUri(cert); LOG.info("CRL's URL for " + CertificateIdentifier.getIdAsString(cert) + " : " + crlURL); if (crlURL == null) { return null; }//from w w w . j av a 2 s . com X509CRL x509CRL; boolean http = crlURL.startsWith("http://") || crlURL.startsWith("https://"); if (dataLoader != null && http) { x509CRL = downloadCrlFromHTTP(crlURL); } else if (http || crlURL.startsWith("ftp://")) { x509CRL = downloadCRLFromURL(crlURL); } else if (crlURL.startsWith("ldap://")) { x509CRL = downloadCRLFromLDAP_(crlURL); } else { LOG.warning("DSS framework only supports HTTP, HTTPS, FTP and LDAP CRL's url."); return null; } if (x509CRL == null) { return null; } try { x509CRL.verify(issuerCert.getPublicKey()); } catch (Exception e) { LOG.warning("The CRL signature is not valid!"); return null; } // assert CRLSign KeyUsage bit final boolean[] keyUsage = issuerCert.getKeyUsage(); if (keyUsage == null || (keyUsage != null && !keyUsage[6])) { LOG.warning("No KeyUsage extension for CRL issuing certificate!"); return null; } return x509CRL; }
From source file:gov.nih.nci.cagrid.gts.service.ProxyPathValidator.java
protected void checkCRL(X509Certificate cert, CertificateRevocationLists crlsList, TrustedCertificates trustedCerts) throws ProxyPathValidatorException { if (crlsList == null) { return;/*from w ww . ja v a2 s . co m*/ } logger.debug("checkCRLs: enter"); // Should not happen, just a sanity check. if (trustedCerts == null) { String err = "Trusted certificates are null, cannot verify CRLs"; logger.error(err); throw new ProxyPathValidatorException(ProxyPathValidatorException.FAILURE, null, err); } String issuerName = cert.getIssuerDN().getName(); X509CRL crl = crlsList.getCrl(issuerName); if (crl == null) { logger.debug("No CRL for certificate"); return; } // get CA cert for the CRL X509Certificate x509Cert = trustedCerts.getCertificate(issuerName); if (x509Cert == null) { // if there is no trusted certs from that CA, then // the chain cannot contain a cert from that CA, // which implies not checking this CRL should be fine. logger.debug("No trusted cert with this CA signature"); return; } // validate CRL try { crl.verify(x509Cert.getPublicKey()); } catch (Exception exp) { logger.error("CRL verification failed"); throw new ProxyPathValidatorException(ProxyPathValidatorException.FAILURE, exp); } Date now = new Date(); // check date validity of CRL if ((crl.getThisUpdate().before(now)) || ((crl.getNextUpdate() != null) && (crl.getNextUpdate().after(now)))) { if (crl.isRevoked(cert)) { throw new ProxyPathValidatorException(ProxyPathValidatorException.REVOKED, cert, "This cert " + cert.getSubjectDN().getName() + " is on a CRL"); } } logger.debug("checkCRLs: exit"); }
From source file:org.ejbca.core.protocol.scep.ProtocolScepHttpTest.java
private void checkScepResponse(byte[] retMsg, String userDN, String _senderNonce, String _transId, boolean crlRep, String digestOid, boolean noca) throws CMSException, OperatorCreationException, NoSuchProviderException, CRLException, InvalidKeyException, NoSuchAlgorithmException, SignatureException, CertificateException { // Parse response message ///*www . j a v a 2s . com*/ CMSSignedData s = new CMSSignedData(retMsg); // The signer, i.e. the CA, check it's the right CA SignerInformationStore signers = s.getSignerInfos(); @SuppressWarnings("unchecked") Collection<SignerInformation> col = signers.getSigners(); assertTrue(col.size() > 0); Iterator<SignerInformation> iter = col.iterator(); SignerInformation signerInfo = iter.next(); // Check that the message is signed with the correct digest alg assertEquals(signerInfo.getDigestAlgOID(), digestOid); SignerId sinfo = signerInfo.getSID(); // Check that the signer is the expected CA assertEquals(CertTools.stringToBCDNString(cacert.getIssuerDN().getName()), CertTools.stringToBCDNString(sinfo.getIssuer().toString())); // Verify the signature JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME); JcaSignerInfoVerifierBuilder jcaSignerInfoVerifierBuilder = new JcaSignerInfoVerifierBuilder( calculatorProviderBuilder.build()).setProvider(BouncyCastleProvider.PROVIDER_NAME); boolean ret = signerInfo.verify(jcaSignerInfoVerifierBuilder.build(cacert.getPublicKey())); assertTrue(ret); // Get authenticated attributes AttributeTable tab = signerInfo.getSignedAttributes(); // --Fail info Attribute attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_failInfo)); // No failInfo on this success message assertNull(attr); // --Message type attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_messageType)); assertNotNull(attr); ASN1Set values = attr.getAttrValues(); assertEquals(values.size(), 1); ASN1String str = DERPrintableString.getInstance((values.getObjectAt(0))); String messageType = str.getString(); assertEquals("3", messageType); // --Success status attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_pkiStatus)); assertNotNull(attr); values = attr.getAttrValues(); assertEquals(values.size(), 1); str = DERPrintableString.getInstance((values.getObjectAt(0))); assertEquals(ResponseStatus.SUCCESS.getStringValue(), str.getString()); // --SenderNonce attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_senderNonce)); assertNotNull(attr); values = attr.getAttrValues(); assertEquals(values.size(), 1); ASN1OctetString octstr = ASN1OctetString.getInstance(values.getObjectAt(0)); // SenderNonce is something the server came up with, but it should be 16 // chars assertTrue(octstr.getOctets().length == 16); // --Recipient Nonce attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_recipientNonce)); assertNotNull(attr); values = attr.getAttrValues(); assertEquals(values.size(), 1); octstr = ASN1OctetString.getInstance(values.getObjectAt(0)); // recipient nonce should be the same as we sent away as sender nonce assertEquals(_senderNonce, new String(Base64.encode(octstr.getOctets()))); // --Transaction ID attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_transId)); assertNotNull(attr); values = attr.getAttrValues(); assertEquals(values.size(), 1); str = DERPrintableString.getInstance((values.getObjectAt(0))); // transid should be the same as the one we sent assertEquals(_transId, str.getString()); // // Check different message types // if (messageType.equals("3")) { // First we extract the encrypted data from the CMS enveloped data // contained // within the CMS signed data final CMSProcessable sp = s.getSignedContent(); final byte[] content = (byte[]) sp.getContent(); final CMSEnvelopedData ed = new CMSEnvelopedData(content); final RecipientInformationStore recipients = ed.getRecipientInfos(); Store certstore; @SuppressWarnings("unchecked") Collection<RecipientInformation> c = recipients.getRecipients(); assertEquals(c.size(), 1); Iterator<RecipientInformation> riIterator = c.iterator(); byte[] decBytes = null; RecipientInformation recipient = riIterator.next(); JceKeyTransEnvelopedRecipient rec = new JceKeyTransEnvelopedRecipient(key1.getPrivate()); rec.setContentProvider(BouncyCastleProvider.PROVIDER_NAME); decBytes = recipient.getContent(rec); // This is yet another CMS signed data CMSSignedData sd = new CMSSignedData(decBytes); // Get certificates from the signed data certstore = sd.getCertificates(); if (crlRep) { // We got a reply with a requested CRL @SuppressWarnings("unchecked") final Collection<X509CRLHolder> crls = (Collection<X509CRLHolder>) sd.getCRLs().getMatches(null); assertEquals(crls.size(), 1); final Iterator<X509CRLHolder> it = crls.iterator(); // CRL is first (and only) final X509CRL retCrl = new JcaX509CRLConverter().getCRL(it.next()); log.info("Got CRL with DN: " + retCrl.getIssuerDN().getName()); // check the returned CRL assertEquals(CertTools.getSubjectDN(cacert), CertTools.getIssuerDN(retCrl)); retCrl.verify(cacert.getPublicKey()); } else { // We got a reply with a requested certificate @SuppressWarnings("unchecked") final Collection<X509CertificateHolder> certs = (Collection<X509CertificateHolder>) certstore .getMatches(null); // EJBCA returns the issued cert and the CA cert (cisco vpn // client requires that the ca cert is included) if (noca) { assertEquals(certs.size(), 1); } else { assertEquals(certs.size(), 2); } final Iterator<X509CertificateHolder> it = certs.iterator(); // Issued certificate must be first boolean verified = false; boolean gotcacert = false; JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter(); while (it.hasNext()) { X509Certificate retcert = jcaX509CertificateConverter.getCertificate(it.next()); log.info("Got cert with DN: " + retcert.getSubjectDN().getName()); // check the returned certificate String subjectdn = CertTools.stringToBCDNString(retcert.getSubjectDN().getName()); if (CertTools.stringToBCDNString(userDN).equals(subjectdn)) { // issued certificate assertEquals(CertTools.stringToBCDNString(userDN), subjectdn); assertEquals(CertTools.getSubjectDN(cacert), CertTools.getIssuerDN(retcert)); retcert.verify(cacert.getPublicKey()); assertTrue(checkKeys(key1.getPrivate(), retcert.getPublicKey())); verified = true; } else { // ca certificate assertEquals(CertTools.getSubjectDN(cacert), CertTools.getSubjectDN(retcert)); gotcacert = true; } } assertTrue(verified); if (noca) { assertFalse(gotcacert); } else { assertTrue(gotcacert); } } } }
From source file:org.xdi.oxauth.cert.validation.CRLCertificateVerifier.java
private boolean validateCRL(X509CRL x509crl, X509Certificate certificate, X509Certificate issuerCertificate, Date validationDate) {/*from w w w. ja v a 2s .c o m*/ Principal subjectX500Principal = certificate.getSubjectX500Principal(); if (x509crl == null) { log.error("No CRL found for certificate '" + subjectX500Principal + "'"); return false; } if (log.isTraceEnabled()) { try { log.trace("CRL number: " + getCrlNumber(x509crl)); } catch (IOException ex) { log.error("Failed to get CRL number", ex); } } if (!x509crl.getIssuerX500Principal().equals(issuerCertificate.getSubjectX500Principal())) { log.error("The CRL must be signed by the issuer '" + subjectX500Principal + "' but instead is signed by '" + x509crl.getIssuerX500Principal() + "'"); return false; } try { x509crl.verify(issuerCertificate.getPublicKey()); } catch (Exception ex) { log.error("The signature verification for CRL cannot be performed", ex); return false; } log.debug("CRL validationDate: " + validationDate); log.debug("CRL nextUpdate: " + x509crl.getThisUpdate()); log.debug("CRL thisUpdate: " + x509crl.getNextUpdate()); if (x509crl.getNextUpdate() != null && validationDate.after(x509crl.getNextUpdate())) { log.error("CRL is too old"); return false; } if (issuerCertificate.getKeyUsage() == null) { log.error("There is no KeyUsage extension for certificate '" + subjectX500Principal + "'"); return false; } if (!issuerCertificate.getKeyUsage()[6]) { log.error("cRLSign bit is not set for CRL certificate'" + subjectX500Principal + "'"); return false; } return true; }