List of usage examples for java.security.cert CertPath getCertificates
public abstract List<? extends Certificate> getCertificates();
From source file:MainClass.java
public static void main(String args[]) throws Exception { CertificateFactory cf = CertificateFactory.getInstance("X.509"); List mylist = new ArrayList(); for (int i = 0; i < args.length; i++) { FileInputStream in = new FileInputStream(args[i]); Certificate c = cf.generateCertificate(in); mylist.add(c);/*from w w w . jav a 2s .c om*/ } CertPath cp = cf.generateCertPath(mylist); List cplist = cp.getCertificates(); Object[] o = cplist.toArray(); for (int i = 0; i < o.length; i++) { X509Certificate c = (X509Certificate) o[i]; System.out.println(c.getSubjectDN()); byte[] pbk = c.getPublicKey().getEncoded(); for (int j = 0; j < pbk.length; j++) { System.out.print(pbk[j] + ","); } System.out.println("\nIssued by " + c.getIssuerDN()); } }
From source file:net.shirayu.android.WlanLogin.MyHttpClient.java
public static X509Certificate readPem(InputStream stream) throws CertificateException, NoSuchProviderException, IOException { CertPath cp; try {/* ww w.j a v a 2s.c o m*/ CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC"); cp = cf.generateCertPath(stream, "PEM"); } finally { stream.close(); } List<? extends Certificate> certs = cp.getCertificates(); if (certs.size() < 1) { throw new CertificateException("Certificate list is empty"); } else if (certs.size() > 1) { throw new CertificateException("Intermediate certificate is not allowed"); } if (certs.get(0) instanceof X509Certificate) { X509Certificate cert = (X509Certificate) certs.get(0); cert.checkValidity(); return cert; } else { throw new CertificateException("Certificate is not X509Certificate"); } }
From source file:net.sf.keystore_explorer.crypto.x509.X509CertUtil.java
private static X509Certificate[] loadCertificatesPkiPath(InputStream is) throws CryptoException { try {/*w w w .j av a 2 s. co m*/ CertificateFactory cf = CertificateFactory.getInstance(X509_CERT_TYPE, BOUNCY_CASTLE.jce()); CertPath certPath = cf.generateCertPath(is, PKI_PATH_ENCODING); List<? extends Certificate> certs = certPath.getCertificates(); ArrayList<X509Certificate> loadedCerts = new ArrayList<X509Certificate>(); for (Iterator<? extends Certificate> itr = certs.iterator(); itr.hasNext();) { X509Certificate cert = (X509Certificate) itr.next(); if (cert != null) { loadedCerts.add(cert); } } return loadedCerts.toArray(new X509Certificate[loadedCerts.size()]); } catch (CertificateException e) { throw new CryptoException(res.getString("NoLoadPkiPath.exception.message"), e); } catch (NoSuchProviderException e) { throw new CryptoException(res.getString("NoLoadPkiPath.exception.message"), e); } finally { IOUtils.closeQuietly(is); } }
From source file:it.anyplace.sync.core.security.KeystoreHandler.java
public void checkSocketCerificate(SSLSocket socket, String deviceId) throws SSLPeerUnverifiedException, CertificateException { SSLSession session = socket.getSession(); List<Certificate> certs = Arrays.asList(session.getPeerCertificates()); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); CertPath certPath = certificateFactory.generateCertPath(certs); Certificate certificate = certPath.getCertificates().get(0); checkArgument(certificate instanceof X509Certificate); byte[] derData = certificate.getEncoded(); String deviceIdFromCertificate = derDataToDeviceIdString(derData); logger.trace("remote pem certificate =\n{}", derToPem(derData)); checkArgument(equal(deviceIdFromCertificate, deviceId), "device id mismatch! expected = %s, got = %s", deviceId, deviceIdFromCertificate); logger.debug("remote ssl certificate match deviceId = {}", deviceId); }
From source file:com.alfaariss.oa.profile.aselect.ws.security.OACrypto.java
/** * Construct an array of certificate's./*from w w w . j a v a 2s . c o m*/ * @see Crypto#getX509Certificates(byte[], boolean) */ public X509Certificate[] getX509Certificates(byte[] data, boolean reverse) throws WSSecurityException { X509Certificate[] certs = null; try { InputStream in = new ByteArrayInputStream(data); CertPath path = getCertificateFactory().generateCertPath(in); List<? extends Certificate> certificates = path.getCertificates(); certs = new X509Certificate[certificates.size()]; int i = 0, size = certificates.size(); for (X509Certificate cert : certs) certs[(reverse) ? (size - 1 - i) : i] = cert; } catch (CertificateException e) { throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE, "parseError", null, e); } return certs; }
From source file:mitm.application.djigzo.ws.impl.CertificateValidatorWSImpl.java
@Override @StartTransaction/* w w w . j a v a 2s .c o m*/ public X509CertificateDTO getIssuerCertificate(CertificateStore store, String thumbprint) throws WebServiceCheckedException { X509Certificate certificate = getCertificate(store, thumbprint); if (certificate == null) { throw new WebServiceCheckedException("Certificate not found"); } X509CertificateDTO issuerDTO = null; try { CertificatePathBuilder pathBuilder = pKISecurityServices.getCertificatePathBuilderFactory() .createCertificatePathBuilder(); CertPathBuilderResult pathBuilderResult = pathBuilder.buildPath(certificate); CertPath certPath = pathBuilderResult.getCertPath(); if (certPath != null) { X509Certificate issuer = null; CertificateStore issuerStore = null; List<? extends Certificate> path = certPath.getCertificates(); if (CollectionUtils.isNotEmpty(path)) { if (CollectionUtils.getSize(path) == 1) { /* * Since there is only one certificate (the certificate itself) we need * to check whether there is a root in the path */ if (pathBuilderResult instanceof PKIXCertPathBuilderResult) { TrustAnchor trustAnchor = ((PKIXCertPathBuilderResult) pathBuilderResult) .getTrustAnchor(); if (trustAnchor != null) { issuer = trustAnchor.getTrustedCert(); issuerStore = CertificateStore.ROOTS; } } } else { issuer = (X509Certificate) path.get(1); issuerStore = CertificateStore.CERTIFICATES; } } if (issuer != null) { issuerDTO = certificateDTOBuilder.buildCertificateDTO(issuer, null); issuerDTO.setCertificateStore(issuerStore); } } } catch (CertPathBuilderException e) { /* * Log on debug level because CertPathBuilderException is for example thrown * when trying to get the issuer of a root for example */ logger.debug("getIssuer failed.", e); } return issuerDTO; }
From source file:mitm.application.djigzo.workflow.impl.KeyAndCertificateWorkflowImpl.java
private void getPFXTransacted(Collection<X509Certificate> certificates, char[] password, boolean includeRoot, OutputStream pfx) throws KeyStoreException { try {//from w w w .j a v a2 s . co m KeyStore keyStore = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12"); keyStore.load(null); for (X509Certificate certificate : certificates) { if (certificate == null) { continue; } X509CertStoreEntry entry = keyAndCertStore.getByCertificate(certificate); if (entry != null && entry.getCertificate() != null) { KeyAndCertificate keyAndCertificate = keyAndCertStore.getKeyAndCertificate(entry); if (keyAndCertificate != null) { if (!certificate.equals(keyAndCertificate.getCertificate())) { throw new IllegalStateException("Certificate mismatch."); } X509Certificate[] chain = null; /* * Build a certificate chain so we add the chain (if valid) */ try { CertificatePathBuilder pathBuilder = pathBuilderFactory.createCertificatePathBuilder(); CertPathBuilderResult pathBuilderResult = pathBuilder.buildPath(certificate); X509Certificate root = null; if (includeRoot && pathBuilderResult instanceof PKIXCertPathBuilderResult) { TrustAnchor trustAnchor = ((PKIXCertPathBuilderResult) pathBuilderResult) .getTrustAnchor(); if (trustAnchor != null) { root = trustAnchor.getTrustedCert(); } } CertPath certPath = pathBuilderResult.getCertPath(); if (certPath != null && CollectionUtils.isNotEmpty(certPath.getCertificates())) { List<X509Certificate> completePath = new LinkedList<X509Certificate>(); for (Certificate fromPath : certPath.getCertificates()) { if (!(fromPath instanceof X509Certificate)) { /* * only X509Certificates are supported */ continue; } completePath.add((X509Certificate) fromPath); } if (root != null && includeRoot) { completePath.add(root); } chain = new X509Certificate[completePath.size()]; chain = completePath.toArray(chain); } } catch (CertPathBuilderException e) { logger.warn( "Could not build a path. Message: " + ExceptionUtils.getRootCauseMessage(e)); } if (ArrayUtils.getLength(chain) == 0) { chain = new X509Certificate[] { certificate }; } String alias = X509CertificateInspector.getThumbprint(certificate); if (keyAndCertificate.getPrivateKey() != null) { keyStore.setKeyEntry(alias, keyAndCertificate.getPrivateKey(), password, chain); } else { keyStore.setCertificateEntry(alias, certificate); } } } } keyStore.store(pfx, password); } catch (NoSuchAlgorithmException e) { throw new KeyStoreException(e); } catch (CertificateException e) { throw new KeyStoreException(e); } catch (IOException e) { throw new KeyStoreException(e); } catch (CertStoreException e) { throw new KeyStoreException(e); } catch (NoSuchProviderException e) { throw new NoSuchProviderRuntimeException(e); } catch (SecurityFactoryFactoryException e) { throw new KeyStoreException(e); } }
From source file:mitm.common.security.certificate.validator.PKITrustCheckCertificateValidatorImpl.java
private boolean isBlackListed(CertPath certPath) throws CTLException { if (ctl == null) { return false; }/* w w w .j a v a2 s. c om*/ List<? extends Certificate> certificates = certPath.getCertificates(); for (int i = 0; i < certificates.size(); i++) { Certificate certificate = certificates.get(i); if (!(certificate instanceof X509Certificate)) { logger.warn("Only X509Certificates can be black listed."); continue; } CTLValidityResult result = ctl.checkValidity((X509Certificate) certificate); if (CTLValidity.INVALID == result.getValidity()) { /* * If the certificate is the first it's not an intermediate. */ String failureMessage = i == 0 ? result.getMessage() : "Intermediate " + result.getMessage(); reportFailure(failureMessage); return true; } } return false; }
From source file:mitm.application.djigzo.james.mailets.SMIMESign.java
private X509Certificate[] getCertificateChain(X509Certificate signingCertificate) { X509Certificate[] chain = null; try {//w w w . ja va 2 s. c om /* * Use CertificatePathBuilderFactory instead of PKITrustCheckCertificateValidator because we * assume that the signing certificate was already checked for revocation etc. * CertificatePathBuilderFactory is faster than PKITrustCheckCertificateValidator */ CertificatePathBuilder pathBuilder = certificatePathBuilderFactory.createCertificatePathBuilder(); CertPathBuilderResult pathBuilderResult = pathBuilder.buildPath(signingCertificate); CertPath certPath = pathBuilderResult.getCertPath(); if (certPath != null && CollectionUtils.isNotEmpty(certPath.getCertificates())) { X509Certificate root = null; if (addRoot && pathBuilderResult instanceof PKIXCertPathBuilderResult) { TrustAnchor trustAnchor = ((PKIXCertPathBuilderResult) pathBuilderResult).getTrustAnchor(); if (trustAnchor != null) { root = trustAnchor.getTrustedCert(); } } List<X509Certificate> completePath = new LinkedList<X509Certificate>(); for (Certificate fromPath : certPath.getCertificates()) { if (!(fromPath instanceof X509Certificate)) { /* * only X509Certificates are supported */ continue; } completePath.add((X509Certificate) fromPath); } if (root != null && addRoot) { completePath.add(root); } chain = new X509Certificate[completePath.size()]; chain = completePath.toArray(chain); } } catch (CertPathBuilderException e) { if (getLogger().isDebugEnabled()) { getLogger().warn("Error building path for signing certificate.", e); } else { getLogger().warn( "Error building path for signing certificate. " + ExceptionUtils.getRootCauseMessage(e)); } } if (chain == null) { chain = new X509Certificate[] { signingCertificate }; } return chain; }
From source file:mitm.common.security.crl.PKIXRevocationChecker.java
@Override public RevocationResult getRevocationStatus(CertPath certPath, TrustAnchor trustAnchor, Date now) throws CRLException { Check.notNull(certPath, "certPath"); Check.notNull(trustAnchor, "trustAnchor"); List<? extends Certificate> certificates = certPath.getCertificates(); RevocationResult revocationResult = new RevocationResultImpl(certificates.size()); /* /*from w w w . j a v a2s .c o m*/ * Step through all the certificates in the path and check the revocation status of all * the certificates in the path. */ for (int i = 0; i < certificates.size(); i++) { X509Certificate certificate = toX509Certificate(certificates.get(i)); PublicKey issuerPublicKey; X500Principal issuer; X509Certificate issuerCertificate; /* * we need to get the issuer of the current certificate * check if there is a next certificate in the path or that we must use the TrustAnchor */ if ((i + 1) == certificates.size()) { /* this was the last entry from the path so we must use the trust anchor */ if (trustAnchor.getTrustedCert() != null) { issuerCertificate = toX509Certificate(trustAnchor.getTrustedCert()); issuerPublicKey = issuerCertificate.getPublicKey(); issuer = issuerCertificate.getSubjectX500Principal(); } else { /* the TrustAnchor does not contain a certificate but only an issuer and public key */ issuerCertificate = null; issuerPublicKey = trustAnchor.getCAPublicKey(); issuer = trustAnchor.getCA(); } } else { /* get next entry from path ie. the issuer of the current certificate */ issuerCertificate = toX509Certificate(certificates.get(i + 1)); issuerPublicKey = issuerCertificate.getPublicKey(); issuer = issuerCertificate.getSubjectX500Principal(); } /* * sanity check to make sure the CertPath is ordered from end -> final CA * ie that the next certificate signed the previous certificate */ verifyCertificate(certificate, issuerPublicKey); /* * Sanity check. The issuer principal field of the certificate currently checked should * normally be equal to the issuer principal. */ if (!certificate.getIssuerX500Principal().equals(issuer)) { logger.warn("Certificate issuer field is not equal to issuer."); } if (issuerCertificate != null) { Set<KeyUsageType> keyUsage = X509CertificateInspector.getKeyUsage(issuerCertificate); /* * check if issuer is allowed to issue CRLs (only when we have an issuerCertificate, and * a key usage extension) */ if (keyUsage != null && !keyUsage.contains(KeyUsageType.CRLSIGN)) { logger.debug("Issuer is not allowed to issue CRLs."); /* * We will return UNKNOWN status. */ RevocationDetailImpl detail = new RevocationDetailImpl(RevocationStatus.UNKNOWN); revocationResult.getDetails()[i] = detail; /* there is no need to continue because issuer is not allowed to issue CRLs */ break; } } X509CRLSelector crlSelector = new X509CRLSelector(); /* create a selector to find all relevant CRLs that were issued to the same issuer as the certificate */ crlSelector.addIssuer(issuer); try { List<X509CRL> crls = findCRLs(certificate, crlSelector, issuerPublicKey, now); RevocationDetail detail = getRevocationDetail(crls, certificate, issuerCertificate, issuerPublicKey, now); revocationResult.getDetails()[i] = detail; if (detail.getStatus() == RevocationStatus.REVOKED) { logger.warn("Certificate is revoked."); if (logger.isDebugEnabled()) { logger.debug("Revoked certificate: " + certificate); } /* there is no need to continue because the CRL is revoked */ break; } } catch (NoSuchProviderException e) { throw new NoSuchProviderRuntimeException(e); } } if (logger.isDebugEnabled()) { logger.debug("Revocation status for CertPath " + certPath + " and TrustAnchor " + trustAnchor + " is " + revocationResult); } return revocationResult; }