List of usage examples for java.security.cert X509Certificate getSubjectDN
public abstract Principal getSubjectDN();
From source file:AuthSSLProtocolSocketFactory.java
private SSLContext createSSLContext() { try {//from www. java 2 s. c o m KeyManager[] keymanagers = null; TrustManager[] trustmanagers = null; if (this.keystoreUrl != null) { KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword); Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); Certificate[] certs = keystore.getCertificateChain(alias); if (certs != null) { System.out.println("Certificate chain '" + alias + "':"); for (int c = 0; c < certs.length; c++) { if (certs[c] instanceof X509Certificate) { X509Certificate cert = (X509Certificate) certs[c]; System.out.println(" Certificate " + (c + 1) + ":"); System.out.println(" Subject DN: " + cert.getSubjectDN()); System.out.println(" Signature Algorithm: " + cert.getSigAlgName()); System.out.println(" Valid from: " + cert.getNotBefore()); System.out.println(" Valid until: " + cert.getNotAfter()); System.out.println(" Issuer: " + cert.getIssuerDN()); } } } } keymanagers = createKeyManagers(keystore, this.keystorePassword); } if (this.truststoreUrl != null) { KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword); Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); System.out.println("Trusted certificate '" + alias + "':"); Certificate trustedcert = keystore.getCertificate(alias); if (trustedcert != null && trustedcert instanceof X509Certificate) { X509Certificate cert = (X509Certificate) trustedcert; System.out.println(" Subject DN: " + cert.getSubjectDN()); System.out.println(" Signature Algorithm: " + cert.getSigAlgName()); System.out.println(" Valid from: " + cert.getNotBefore()); System.out.println(" Valid until: " + cert.getNotAfter()); System.out.println(" Issuer: " + cert.getIssuerDN()); } } trustmanagers = createTrustManagers(keystore); } SSLContext sslcontext = SSLContext.getInstance("SSL"); sslcontext.init(keymanagers, trustmanagers, null); return sslcontext; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage()); } catch (KeyStoreException e) { e.printStackTrace(); throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage()); } catch (GeneralSecurityException e) { e.printStackTrace(); throw new AuthSSLInitializationError("Key management exception: " + e.getMessage()); } catch (IOException e) { e.printStackTrace(); throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage()); } }
From source file:org.sinekartads.integration.cms.SignCMSonAlfresco.java
private void showCertificate(X509Certificate certificate) { Map<String, String> dns = DNParser.parse(certificate.getSubjectDN()); tracer.info(String.format("subject: %s", dns.get(SinekartaDsObjectIdentifiers.dn_commonName))); tracer.info(String.format("country: %s", dns.get(SinekartaDsObjectIdentifiers.dn_countryName))); tracer.info(String.format("organization: %s", dns.get(SinekartaDsObjectIdentifiers.dn_organizationName))); tracer.info(String.format("organization unit: %s", dns.get(SinekartaDsObjectIdentifiers.dn_organizationUnitName))); tracer.info(String.format("not before: %s", formatDate(certificate.getNotBefore()))); tracer.info(String.format("not after: %s", formatDate(certificate.getNotAfter()))); dns = DNParser.parse(certificate.getIssuerDN()); tracer.info(String.format("issuer: %s", dns.get(SinekartaDsObjectIdentifiers.dn_commonName))); }
From source file:org.glite.slcs.httpclient.ssl.ExtendedX509TrustManager.java
/** * Returns <code>true</code> iff the certificate issuer is in our trust * store and it have signed the cert.//from w ww. ja va2 s. c o m * * @param cert * The X509 certificate to check. * @return <code>true</code> if the certificate issuer is in * trustedIssuers list and have signed the cert. */ protected boolean isCertificateIssuerTrusted(X509Certificate cert) { //TODO: checks CA CRL // checks if an trusted issuer have signed the certificate boolean trusted = false; Iterator issuers = trustedIssuers_.iterator(); while (issuers.hasNext()) { X509Certificate issuer = (X509Certificate) issuers.next(); PublicKey issuerPublicKey = issuer.getPublicKey(); try { if (LOG.isDebugEnabled()) { LOG.debug("checking: " + issuer.getSubjectDN()); } cert.verify(issuerPublicKey); trusted = true; break; } catch (GeneralSecurityException e) { if (LOG.isDebugEnabled()) { LOG.debug(e); } } } if (!trusted) { LOG.warn("No trusted issuer found in TrustStore for: " + cert.getSubjectDN()); } return trusted; }
From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java
@SuppressWarnings("unchecked") public static String validarAssinaturaPKCS7(final byte[] digest, final String digestAlgorithm, final byte[] assinatura, Date dtAssinatura, boolean verificarLCRs) throws InvalidKeyException, SecurityException, CRLException, CertificateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, AplicacaoException, ChainValidationException, IOException, Exception { Map<String, byte[]> map = new HashMap<String, byte[]>(); map.put(digestAlgorithm, digest);//from ww w . j a v a 2s . c o m final CMSSignedData signedData = new CMSSignedData(map, assinatura); Store certs = signedData.getCertificates(); SignerInformationStore signers = signedData.getSignerInfos(); Collection<SignerInformation> c = signers.getSigners(); Iterator<SignerInformation> it = c.iterator(); String sCN = ""; while (it.hasNext()) { SignerInformation signer = it.next(); Collection<X509CertificateHolder> certCollection = certs.getMatches(signer.getSID()); @SuppressWarnings("unused") String ss = signer.getDigestAlgOID(); @SuppressWarnings("unused") String sss = signer.getDigestAlgorithmID().getObjectId().getId(); Iterator<X509CertificateHolder> certIt = certCollection.iterator(); X509CertificateHolder certHolder = certIt.next(); X509Certificate cert = AssinaturaDigital.getX509Certificate(certHolder); if (!signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certHolder))) throw new Exception("Assinatura invlida!"); X509Certificate[] cadeiaTotal = montarCadeiaOrdenadaECompleta(certCollection); final X509ChainValidator cadeia = new X509ChainValidator(cadeiaTotal, /* trustedAnchors */new HashSet(FachadaDeCertificadosAC.getTrustAnchors()), null); cadeia.checkCRL(verificarLCRs); cadeia.validateChain(dtAssinatura); String s2 = cert.getSubjectDN().getName(); s2 = obterNomeExibicao(s2); if (sCN.length() != 0) sCN += ", "; sCN += s2; } return sCN.length() == 0 ? null : sCN; }
From source file:com.netscape.cms.servlet.cert.RenewalProcessor.java
private BigInteger getSerialNumberFromCert(HttpServletRequest request) throws EBaseException { SSLClientCertProvider sslCCP = new SSLClientCertProvider(request); X509Certificate[] certs = sslCCP.getClientCertificateChain(); if (certs == null || certs.length == 0) { CMS.debug("RenewalProcessor: missing SSL client certificate chain"); throw new BadRequestException("Missing SSL client certificate chain"); }// w w w . j a v a2s . c o m CMS.debug("RenewalProcessor: has SSL client cert chain"); // shouldn't expect leaf cert to be always at the // same location X509Certificate clientCert = null; for (X509Certificate cert : certs) { CMS.debug("RenewalProcessor: cert " + cert.getSubjectDN()); clientCert = cert; byte[] extBytes = clientCert.getExtensionValue("2.5.29.19"); // try to see if this is a leaf cert // look for BasicConstraint extension if (extBytes == null) { // found leaf cert CMS.debug("RenewalProcessor: found leaf cert"); break; } CMS.debug("RenewalProcessor: found cert having BasicConstraints ext"); // it's got BasicConstraints extension // so it's not likely to be a leaf cert, // however, check the isCA field regardless try { BasicConstraintsExtension bce = new BasicConstraintsExtension(true, extBytes); if (!(Boolean) bce.get("is_ca")) { CMS.debug("RenewalProcessor: found CA cert in chain"); break; } // else found a ca cert, continue } catch (Exception e) { CMS.debug("RenewalProcessor: Invalid certificate extension:" + e); throw new BadRequestException("Invalid certificate extension: " + e.getMessage(), e); } } // clientCert cannot be null here return clientCert.getSerialNumber(); }
From source file:com.utest.webservice.client.rest.AuthSSLProtocolSocketFactory.java
@SuppressWarnings("unchecked") private SSLContext createSSLContext() { try {/* ww w. j av a 2 s . com*/ KeyManager[] keymanagers = null; TrustManager[] trustmanagers = null; if (this.keystoreUrl != null) { KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword); if (true) { Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); Certificate[] certs = keystore.getCertificateChain(alias); if (certs != null) { System.out.println("Certificate chain '" + alias + "':"); for (int c = 0; c < certs.length; c++) { if (certs[c] instanceof X509Certificate) { X509Certificate cert = (X509Certificate) certs[c]; System.out.println(" Certificate " + (c + 1) + ":"); System.out.println(" Subject DN: " + cert.getSubjectDN()); System.out.println(" Signature Algorithm: " + cert.getSigAlgName()); System.out.println(" Valid from: " + cert.getNotBefore()); System.out.println(" Valid until: " + cert.getNotAfter()); System.out.println(" Issuer: " + cert.getIssuerDN()); } } } } } keymanagers = createKeyManagers(keystore, this.keystorePassword); } if (this.truststoreUrl != null) { KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword); if (true) { Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); System.out.println("Trusted certificate '" + alias + "':"); Certificate trustedcert = keystore.getCertificate(alias); if (trustedcert != null && trustedcert instanceof X509Certificate) { X509Certificate cert = (X509Certificate) trustedcert; System.out.println(" Subject DN: " + cert.getSubjectDN()); System.out.println(" Signature Algorithm: " + cert.getSigAlgName()); System.out.println(" Valid from: " + cert.getNotBefore()); System.out.println(" Valid until: " + cert.getNotAfter()); System.out.println(" Issuer: " + cert.getIssuerDN()); } } } trustmanagers = createTrustManagers(keystore); } SSLContext sslcontext = SSLContext.getInstance("SSL"); sslcontext.init(keymanagers, trustmanagers, null); return sslcontext; } catch (NoSuchAlgorithmException e) { System.out.println(e.getMessage()); throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage()); } catch (KeyStoreException e) { System.out.println(e.getMessage()); throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage()); } catch (GeneralSecurityException e) { System.out.println(e.getMessage()); throw new AuthSSLInitializationError("Key management exception: " + e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage()); } }
From source file:org.waveprotocol.wave.crypto.WaveSignatureVerifier.java
/** * Verifies that the given certificate was issued to the given authority. * @param authority the authority to which the certificate was issued, * e.g., a domain name./*from w w w .ja v a 2 s . com*/ * @param certificate the {@link X509Certificate} * @throws SignatureException if the authority doesn't match the certificate. */ private void verifyMatchingAuthority(String authority, X509Certificate certificate) throws SignatureException { String cn = getCommonNameFromDistinguishedName(certificate.getSubjectX500Principal().getName()); if (cn == null) { throw new SignatureException( "no common name found in signer " + "certificate " + certificate.getSubjectDN().toString()); } if (cn.equals(authority)) { return; } if (authorityMatchesSubjectAlternativeNames(authority, certificate)) { return; } if (authorityMatchesWildcardCN(authority, cn)) { return; } throw new SignatureException( "expected " + authority + " as CN or alternative name in cert, but didn't find it"); }
From source file:com.quarterfull.newsAndroid.ssl.MemorizingTrustManager.java
void storeCert(X509Certificate[] chain) { // add all certs from chain to appKeyStore try {//from w w w.j a va 2 s .com for (X509Certificate c : chain) appKeyStore.setCertificateEntry(c.getSubjectDN().toString(), c); } catch (KeyStoreException e) { Log.e(TAG, "storeCert(" + Arrays.toString(chain) + ")", e); return; } // reload appTrustManager appTrustManager = getTrustManager(appKeyStore); // store KeyStore to file try { java.io.FileOutputStream fos = new java.io.FileOutputStream(keyStoreFile); appKeyStore.store(fos, "MTM".toCharArray()); fos.close(); } catch (Exception e) { Log.e(TAG, "storeCert(" + keyStoreFile + ")", e); } }
From source file:com.quarterfull.newsAndroid.ssl.MemorizingTrustManager.java
private String certChainMessage(final X509Certificate[] chain, CertificateException cause) { Throwable e = cause;// www . j a v a 2 s.c om Log.d(TAG, "certChainMessage for " + e); StringBuilder si = new StringBuilder(); if (e.getCause() != null) { e = e.getCause(); si.append(e.getLocalizedMessage()); //si.append("\n"); } for (X509Certificate c : chain) { si.append("\n\n"); si.append(c.getSubjectDN().toString()); si.append("\nMD5: "); si.append(certHash(c, "MD5")); si.append("\nSHA1: "); si.append(certHash(c, "SHA-1")); si.append("\nSigned by: "); si.append(c.getIssuerDN().toString()); } return si.toString(); }
From source file:org.opendaylight.aaa.cert.impl.ODLKeyTool.java
public String generateCertificateReq(final String keyStoreName, final String keyStorePwd, final String keyAlias, final String signAlg, final boolean withTag) { try {/* ww w.jav a2 s .c o m*/ final KeyStore ctlKeyStore = KeyStore.getInstance("JKS"); final FileInputStream fInputStream = new FileInputStream(workingDir + keyStoreName); ctlKeyStore.load(fInputStream, keyStorePwd.toCharArray()); if (ctlKeyStore.containsAlias(keyAlias)) { final X509Certificate odlCert = (X509Certificate) ctlKeyStore.getCertificate(keyAlias); final PublicKey pubKey = odlCert.getPublicKey(); final PrivateKey privKey = (PrivateKey) ctlKeyStore.getKey(keyAlias, keyStorePwd.toCharArray()); final String subject = odlCert.getSubjectDN().getName(); final X509Name xname = new X509Name(subject); final String signatureAlgorithm = signAlg; final PKCS10CertificationRequest csr = new PKCS10CertificationRequest(signatureAlgorithm, xname, pubKey, null, privKey); final String certReq = DatatypeConverter.printBase64Binary(csr.getEncoded()); if (withTag) { final StringBuilder sb = new StringBuilder(); sb.append(KeyStoreConstant.BEGIN_CERTIFICATE_REQUEST); sb.append("\n"); sb.append(certReq); sb.append("\n"); sb.append(KeyStoreConstant.END_CERTIFICATE_REQUEST); return sb.toString(); } return certReq; } LOG.info("{} KeyStore does not contain alias {}", keyStoreName, keyAlias); return null; } catch (NoSuchAlgorithmException | CertificateException | IOException | KeyStoreException | UnrecoverableKeyException | InvalidKeyException | NoSuchProviderException | SignatureException e) { LOG.error("Failed to generate certificate request {}", e.getMessage()); return null; } }