List of usage examples for java.security KeyStore getCertificateChain
public final Certificate[] getCertificateChain(String alias) throws KeyStoreException
From source file:org.eclipse.gyrex.http.jetty.internal.admin.CertificateDefinition.java
@Override public String getInfo() { try {//from w ww. j a v a2 s . com final StrBuilder certInfo = new StrBuilder(); final KeyStore ks = getKeyStore(); final Enumeration aliases = ks.aliases(); while (aliases.hasMoreElements()) { final String alias = (String) aliases.nextElement(); if (!certInfo.isEmpty()) { certInfo.append(", "); } // certInfo.append(alias).append(": "); if (ks.isKeyEntry(alias)) { Certificate[] chain = ks.getCertificateChain(alias); if (null == chain) { final Certificate certificate = ks.getCertificate(alias); chain = new Certificate[] { certificate }; } for (int i = 0; i < chain.length; i++) { if (i > 0) { certInfo.append(" "); } final Certificate certificate = chain[i]; if (certificate instanceof X509Certificate) { final X509Certificate x509 = (X509Certificate) certificate; final X500PrincipalHelper helper = new X500PrincipalHelper( x509.getSubjectX500Principal()); certInfo.append(helper.getCN()); certInfo.append(", valid till ").append(TO_STRING_FORMAT.format(x509.getNotAfter())); } else { certInfo.append("INVALID"); } } } else { certInfo.append("IGNORED"); } } return StringUtils.trim(certInfo.toString()); } catch (final Exception e) { return ExceptionUtils.getRootCauseMessage(e); } }
From source file:org.codice.ddf.admin.insecure.defaults.service.KeystoreValidator.java
private List<Certificate[]> getKeystoreCertificatesChains(KeyStore keystore) { List<Certificate[]> keystoreCertificateChains = new ArrayList<>(); try {// ww w. j a v a 2 s. c om Enumeration<String> aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); Certificate[] certificateChain = keystore.getCertificateChain(alias); if (certificateChain != null) { keystoreCertificateChains.add(certificateChain); } else { Certificate certificate = keystore.getCertificate(alias); keystoreCertificateChains.add(new Certificate[] { certificate }); } } } catch (KeyStoreException e) { LOGGER.warn(String.format(GENERIC_INSECURE_DEFAULTS_MSG, keystorePath), e); } return keystoreCertificateChains; }
From source file:com.utest.webservice.client.rest.AuthSSLProtocolSocketFactory.java
@SuppressWarnings("unchecked") private SSLContext createSSLContext() { try {// w w w . j a va 2 s . c o m 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.wso2.carbon.is.migration.util.SecondaryUserstoreCryptoUtil.java
/** * Encrypt a given plain text/* w ww . j av a 2 s.c o m*/ * * @param plainTextBytes The plaintext bytes to be encrypted * @param cipherTransformation The transformation that need to encrypt. If it is null, RSA is used as default * @param returnSelfContainedCipherText Create self-contained cipher text if true, return simple encrypted * ciphertext otherwise. * @return The cipher text bytes * @throws CryptoException On error during encryption */ public byte[] encrypt(byte[] plainTextBytes, String cipherTransformation, boolean returnSelfContainedCipherText) throws CryptoException { byte[] encryptedKey; try { Cipher keyStoreCipher; KeyStore keyStore; Certificate[] certs; KeyStoreManager keyMan = KeyStoreManager.getInstance(MultitenantConstants.SUPER_TENANT_ID, ISMigrationServiceDataHolder.getServerConfigurationService(), ISMigrationServiceDataHolder.getRegistryService()); keyStore = keyMan.getPrimaryKeyStore(); certs = keyStore.getCertificateChain(primaryKeyStoreAlias); boolean isCipherTransformEnabled = false; if (cipherTransformation != null) { if (log.isDebugEnabled()) { log.debug("Cipher transformation for encryption : " + cipherTransformation); } keyStoreCipher = Cipher.getInstance(cipherTransformation, "BC"); isCipherTransformEnabled = true; } else { if (log.isDebugEnabled()) { log.debug("Default Cipher transformation for encryption : RSA"); } keyStoreCipher = Cipher.getInstance("RSA", "BC"); } keyStoreCipher.init(Cipher.ENCRYPT_MODE, certs[0].getPublicKey()); if (isCipherTransformEnabled && plainTextBytes.length == 0) { encryptedKey = "".getBytes(); if (log.isDebugEnabled()) { log.debug("Empty value for plainTextBytes null will persist to DB"); } } else { encryptedKey = keyStoreCipher.doFinal(plainTextBytes); } if (isCipherTransformEnabled && returnSelfContainedCipherText) { encryptedKey = CryptoUtil.getDefaultCryptoUtil().createSelfContainedCiphertext(encryptedKey, cipherTransformation, certs[0]); } } catch (Exception e) { throw new CryptoException("Error during encryption", e); } return encryptedKey; }
From source file:gov.nist.toolkit.soap.axis2.AuthSSLProtocolSocketFactory.java
private SSLContext createSSLContext() throws IOException { try {/*from ww w . j a v a 2 s.com*/ KeyManager[] keymanagers = null; TrustManager[] trustmanagers = null; if (this.keystoreUrl != null) { KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword); if (LOG.isDebugEnabled()) { Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); Certificate[] certs = keystore.getCertificateChain(alias); if (certs != null) { LOG.debug("Certificate chain '" + alias + "':"); for (int c = 0; c < certs.length; c++) { if (certs[c] instanceof X509Certificate) { X509Certificate cert = (X509Certificate) certs[c]; LOG.debug(" Certificate " + (c + 1) + ":"); LOG.debug(" Subject DN: " + cert.getSubjectDN()); LOG.debug(" Signature Algorithm: " + cert.getSigAlgName()); LOG.debug(" Valid from: " + cert.getNotBefore()); LOG.debug(" Valid until: " + cert.getNotAfter()); LOG.debug(" Issuer: " + cert.getIssuerDN()); } } } } } keymanagers = createKeyManagers(keystore, this.keystorePassword); } if (this.truststoreUrl != null) { KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword); if (LOG.isDebugEnabled()) { Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); LOG.debug("Trusted certificate '" + alias + "':"); Certificate trustedcert = keystore.getCertificate(alias); if (trustedcert != null && trustedcert instanceof X509Certificate) { X509Certificate cert = (X509Certificate) trustedcert; LOG.debug(" Subject DN: " + cert.getSubjectDN()); LOG.debug(" Signature Algorithm: " + cert.getSigAlgName()); LOG.debug(" Valid from: " + cert.getNotBefore()); LOG.debug(" Valid until: " + cert.getNotAfter()); LOG.debug(" Issuer: " + cert.getIssuerDN()); } } } trustmanagers = createTrustManagers(keystore); } SSLContext sslcontext = SSLContext.getInstance("SSL"); sslcontext.init(keymanagers, trustmanagers, null); return sslcontext; } catch (NoSuchAlgorithmException e) { LOG.error(e.getMessage(), e); throw new IOException("Unsupported algorithm exception: " + e.getMessage()); } catch (KeyStoreException e) { LOG.error(e.getMessage(), e); throw new IOException("Keystore exception: " + e.getMessage()); } catch (GeneralSecurityException e) { LOG.error(e.getMessage(), e); throw new IOException("Key management exception: " + e.getMessage()); } catch (IOException e) { LOG.error(e.getMessage(), e); throw new IOException("I/O error reading keystore/truststore file: " + e.getMessage()); } }
From source file:io.pivotal.springcloud.ssl.CloudFoundryCertificateTruster.java
/** * import trust from truststore file/*from w w w .j a va2s.co m*/ * * @param applicationContext * @param trustStore * @param trustStorePassword */ private void trustCertificatesFromStoreInternal(ConfigurableApplicationContext applicationContext, String trustStore, String trustStorePassword) { if (trustStore != null) { try { KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(applicationContext.getResource(trustStore).getInputStream(), trustStorePassword.toCharArray()); Enumeration<String> aliases = keystore.aliases(); List<X509Certificate> certCollect = new ArrayList<X509Certificate>(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); Certificate[] certs = keystore.getCertificateChain(alias); if (certs != null && certs.length > 0) for (Certificate cert : certs) if (cert instanceof X509Certificate) certCollect.add((X509Certificate) cert); Certificate cert = keystore.getCertificate(alias); if (cert != null && cert instanceof X509Certificate) { certCollect.add((X509Certificate) cert); } } if (certCollect.size() > 0) sslCertificateTruster.appendToTruststoreInternal(certCollect.toArray(new X509Certificate[0])); } catch (Exception e) { log.error("trusting trustore at {}:{} failed", trustStore, trustStorePassword, e); } } }
From source file:ch.cyberduck.core.ssl.CertificateStoreX509KeyManager.java
public X509Certificate getCertificate(final String alias, final String[] keyTypes, final Principal[] issuers) { try {//from ww w . j a v a 2 s . c o m final KeyStore store; try { store = this.getKeystore(); } catch (IOException e) { return null; } final Certificate cert = store.getCertificate(alias); if (this.matches(cert, keyTypes, issuers)) { return (X509Certificate) cert; } for (Certificate c : store.getCertificateChain(alias)) { if (c instanceof X509Certificate) { if (this.matches(c, keyTypes, issuers)) { return (X509Certificate) cert; } } } } catch (KeyStoreException e) { log.error(String.format("Keystore not loaded %s", e.getMessage())); } if (log.isInfoEnabled()) { log.info(String.format("No matching certificate found for alias %s and issuers %s", alias, Arrays.toString(issuers))); } return null; }
From source file:org.votingsystem.web.ejb.SignatureBean.java
public KeyStoreDto generateElectionKeysStore(EventVS eventVS) throws Exception { //StringUtils.getRandomAlphaNumeric(7).toUpperCase() // _ TODO _ ====== crypto token String eventVSUrl = config.getRestURL() + "/eventVS/id/" + eventVS.getId(); String strSubjectDNRoot = format("CN=eventVSUrl:{0}, OU=Elections", eventVSUrl); KeyStore keyStore = KeyStoreUtil.createRootKeyStore(eventVS.getDateBegin(), eventVS.getDateFinish(), password.toCharArray(), keyAlias, strSubjectDNRoot); java.security.cert.Certificate[] chain = keyStore.getCertificateChain(keyAlias); java.security.cert.Certificate cert = chain[0]; return new KeyStoreDto(new KeyStoreVS(keyAlias, KeyStoreUtil.getBytes(keyStore, password.toCharArray()), eventVS.getDateBegin(), eventVS.getDateFinish()), (X509Certificate) cert); }
From source file:org.votingsystem.web.ejb.SignatureBean.java
public void init() throws Exception { Properties properties = new Properties(); URL res = Thread.currentThread().getContextClassLoader().getResource("KeyStore.properties"); log.info("init - res: " + res.toURI()); properties.load(res.openStream());//from w ww . j a v a 2 s . c o m keyAlias = properties.getProperty("vs.signKeyAlias"); password = properties.getProperty("vs.signKeyPassword"); String keyStoreFileName = properties.getProperty("vs.keyStoreFile"); res = Thread.currentThread().getContextClassLoader().getResource(keyStoreFileName); File keyStoreFile = FileUtils.getFileFromBytes(IOUtils.toByteArray(res.openStream())); signedMailGenerator = new SMIMESignedGeneratorVS(FileUtils.getBytesFromFile(keyStoreFile), keyAlias, password.toCharArray(), ContextVS.SIGN_MECHANISM); KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream(keyStoreFile), password.toCharArray()); certChain = new ArrayList<>(); for (java.security.cert.Certificate certificate : keyStore.getCertificateChain(keyAlias)) { checkAuthorityCertDB((X509Certificate) certificate); certChain.add((X509Certificate) certificate); } keyStorePEMCerts = CertUtils.getPEMEncoded(certChain); localServerCertSigner = (X509Certificate) keyStore.getCertificate(keyAlias); currencyAnchors = new HashSet<>(); currencyAnchors.add(new TrustAnchor(localServerCertSigner, null)); Query query = dao.getEM().createNamedQuery("findCertBySerialNumber").setParameter("serialNumber", localServerCertSigner.getSerialNumber().longValue()); serverCertificateVS = dao.getSingleResult(CertificateVS.class, query); serverPrivateKey = (PrivateKey) keyStore.getKey(keyAlias, password.toCharArray()); encryptor = new Encryptor(localServerCertSigner, serverPrivateKey); serverName = config.getServerName(); }
From source file:mitm.BouncyCastleSslEngineSource.java
public void initializeServerCertificates(String commonName, SubjectAlternativeNameHolder subjectAlternativeNames) throws GeneralSecurityException, OperatorCreationException, IOException { KeyStore ks = CertificateHelper.createServerCertificate(commonName, subjectAlternativeNames, authority, caCert, caPrivKey);/*from ww w . j a v a 2s .co m*/ PrivateKey key = (PrivateKey) ks.getKey(authority.alias(), authority.password()); exportPem(authority.aliasFile("-" + commonName + "-key.pem"), key); Object[] certs = ks.getCertificateChain(authority.alias()); exportPem(authority.aliasFile("-" + commonName + "-cert.pem"), certs); }