List of usage examples for java.security KeyStore getCertificate
public final Certificate getCertificate(String alias) throws KeyStoreException
From source file:de.conterra.suite.security.portal.gpx.EmbeddedSAMLTokenIntegrationContext.java
private void initKeyStore(StringAttributeMap stringAttributeMap) { LOGGER.entering("EmbeddedSAMLTokenIntegrationContext", "initKeyStore"); String type = getValFromConfig(CONFIG_PARAM_KEYSTORE_TYPE, "JKS"); String keystoreLoc = getValFromConfig(CONFIG_PARAM_KEYSTORE_LOC, "/gpt/config/keystore.jks"); String keystorePw = getValFromConfig(CONFIG_PARAM_KEYSTORE_PW, "changeit"); String keyAlias = getValFromConfig(CONFIG_PARAM_KEYSTORE_KEY_ALIAS, "gpt-security"); String keyPw = getValFromConfig(CONFIG_PARAM_KEYSTORE_KEY_PW, "changeit"); LOGGER.finest(MessageFormat.format("Instantiating keystore from: {0}", keystoreLoc)); LOGGER.finest(MessageFormat.format("Using certificate alias: {0}", keyAlias)); if ("true".equalsIgnoreCase(getValFromConfig(CONFIG_PARAM_KEYSTORE_PWS_ENCRYPTED, "false"))) { // TODO: test this stuff keystorePw = PC1_Encryptor.decrypt(keystorePw); keyPw = PC1_Encryptor.decrypt(keyPw); }/*from w w w . jav a 2 s. c o m*/ try { KeyStore keystore = KeyStore.getInstance(type); InputStream in = findInputStream(keystoreLoc); try { keystore.load(in, keystorePw.toCharArray()); Certificate cert = keystore.getCertificate(keyAlias); Key key = keystore.getKey(keyAlias, keyPw.toCharArray()); m_applicationCertificate = cert; m_applicationPrivateKey = key; if (cert == null || key == null) { throw new IllegalArgumentException("key alias '" + keyAlias + "> not found!"); } } finally { try { in.close(); } catch (IOException e) { // ignore } } } catch (Exception e) { throw new IllegalStateException("Can't load certificate and key with alias '" + keyAlias + "' from keystore '" + keystoreLoc + "'! Msg" + e, e); } }
From source file:davmail.util.ClientCertificateTest.java
public void testWindowsSmartCard() { try {// w w w . j a va 2s. co m KeyStore ks = KeyStore.getInstance("Windows-MY"); ks.load(null, null); java.util.Enumeration en = ks.aliases(); while (en.hasMoreElements()) { String aliasKey = (String) en.nextElement(); X509Certificate c = (X509Certificate) ks.getCertificate(aliasKey); System.out.println("---> alias : " + aliasKey + " " + c.getSubjectDN()); //PrivateKey key = (PrivateKey) ks.getKey(aliasKey, "Passw0rd".toCharArray()); Certificate[] chain = ks.getCertificateChain(aliasKey); } } catch (Exception ioe) { System.err.println(ioe.getMessage()); } }
From source file:org.opendaylight.aaa.cert.impl.ODLKeyTool.java
public String getCertificate(final String keyStoreName, final String keyStorePwd, final String certAlias, final boolean withTag) { try {//w ww . ja v a 2s. c o m final KeyStore ctlKeyStore = KeyStore.getInstance("JKS"); final FileInputStream fInputStream = new FileInputStream(workingDir + keyStoreName); ctlKeyStore.load(fInputStream, keyStorePwd.toCharArray()); if (ctlKeyStore.containsAlias(certAlias)) { final X509Certificate odlCert = (X509Certificate) ctlKeyStore.getCertificate(certAlias); final String cert = DatatypeConverter.printBase64Binary(odlCert.getEncoded()); if (withTag) { final StringBuilder sb = new StringBuilder(); sb.append(KeyStoreConstant.BEGIN_CERTIFICATE); sb.append("\n"); sb.append(cert); sb.append("\n"); sb.append(KeyStoreConstant.END_CERTIFICATE); return sb.toString(); } return cert; } LOG.info("{} KeyStore does not contain alias {}", keyStoreName, certAlias); return null; } catch (NoSuchAlgorithmException | CertificateException | IOException | KeyStoreException e) { LOG.error("Failed to get Certificate {}", e.getMessage()); return null; } }
From source file:org.wso2.carbon.certificate.mgt.core.impl.KeyStoreReader.java
public Certificate getCACertificate() throws KeystoreException { KeyStore keystore = loadCertificateKeyStore(); Certificate caCertificate;/*w w w . j av a2 s .c o m*/ try { CertificateKeystoreConfig certificateKeystoreConfig = CertificateConfigurationManager.getInstance() .getCertificateKeyStoreConfig(); caCertificate = keystore.getCertificate(certificateKeystoreConfig.getCACertAlias()); } catch (KeyStoreException e) { String errorMsg = "KeyStore issue occurred when loading KeyStore"; throw new KeystoreException(errorMsg, e); } catch (CertificateManagementException e) { String errorMsg = "Unable to find KeyStore configuration in certificate-mgt.config file."; throw new KeystoreException(errorMsg, e); } if (caCertificate == null) { throw new KeystoreException("CA certificate not found in KeyStore"); } return caCertificate; }
From source file:org.wso2.carbon.certificate.mgt.core.impl.KeyStoreReader.java
public Certificate getRACertificate() throws KeystoreException { KeyStore keystore = loadCertificateKeyStore(); Certificate raCertificate;/*from w w w . j a v a2 s .c o m*/ try { CertificateKeystoreConfig certificateKeystoreConfig = CertificateConfigurationManager.getInstance() .getCertificateKeyStoreConfig(); raCertificate = keystore.getCertificate(certificateKeystoreConfig.getRACertAlias()); } catch (KeyStoreException e) { String errorMsg = "KeyStore issue occurred when retrieving RA private key"; throw new KeystoreException(errorMsg, e); } catch (CertificateManagementException e) { String errorMsg = "Unable to find KeyStore configuration in certificate-mgt.config file."; throw new KeystoreException(errorMsg, e); } if (raCertificate == null) { throw new KeystoreException("RA certificate not found in KeyStore"); } return raCertificate; }
From source file:org.wso2.carbon.core.bootup.validator.SystemValidator.java
/** * validate primary keystore with default keystore in the application * here we assume that if the primary keystore did not contain certificate with wso2carbon alias, customer has * modified the default wso2carbon keystore. (means customer using his own keystore) * * @return validated ValidationResult object * @throws CertificateException//from w w w .j ava2 s.co m */ private ValidationResult validateKeystoreFingerprint(String certFingerprint) throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException { ValidationResult result = new ValidationResult(); String msg = null; boolean isValid; KeyStore primaryKeyStore = getPrimaryKeyStore(); X509Certificate wso2CarbonCert = null; if (primaryKeyStore != null) { wso2CarbonCert = (X509Certificate) primaryKeyStore .getCertificate(RegistryResources.SecurityManagement.DEFAULT_SECURITY_CERTIFICATE_ALIAS); } else { log.error("Error loading primary keystore, cannot validate keystore"); } if ((wso2CarbonCert != null) && getCertFingerprint(wso2CarbonCert).equalsIgnoreCase(certFingerprint)) { // this is the fault stage where the client use default wso2carbon keystore msg = "Carbon is configured to use the default keystore (wso2carbon.jks). To maximize security when deploying to a production environment, configure a new keystore with a unique password in the production server profile."; isValid = false; } else { // wso2carbon keystore not present (client has modified the keystore) isValid = true; } result.setValidationMessage(msg); result.setValid(isValid); return result; }
From source file:com.fine47.http.SecureSocketFactory.java
private SecureSocketFactory(String factoryId, KeyStore store, String alias) throws CertificateException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(store); // Loading the CA certificate from store. Certificate rootca = store.getCertificate(alias); // Turn it to X509 format. InputStream is = new ByteArrayInputStream(rootca.getEncoded()); X509Certificate x509ca = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(is); ActivityHttpClient.silentCloseInputStream(is); if (null == x509ca) { throw new CertificateException("Found expired SSL certificate in this store: " + factoryId); }//from w w w .j a v a2s . c o m // Check the CA's validity. x509ca.checkValidity(); // Accepted CA is only the one installed in the store. acceptedIssuers = new X509Certificate[] { x509ca }; // Get the public key. publicKey = rootca.getPublicKey(); sslCtx = SSLContext.getInstance("TLS"); sslCtx.init(null, new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { Exception error = null; if (null == chain || 0 == chain.length) { error = new CertificateException("Certificate chain is invalid"); } else if (null == authType || 0 == authType.length()) { error = new CertificateException("Authentication type is invalid"); } else try { for (X509Certificate cert : chain) { if (ActivityHttpClient.isDebugging()) { Log.d(ActivityHttpClient.LOG_TAG, "Server Certificate Details:"); Log.d(ActivityHttpClient.LOG_TAG, "---------------------------"); Log.d(ActivityHttpClient.LOG_TAG, "IssuerDN: " + cert.getIssuerDN().toString()); Log.d(ActivityHttpClient.LOG_TAG, "SubjectDN: " + cert.getSubjectDN().toString()); Log.d(ActivityHttpClient.LOG_TAG, "Serial Number: " + cert.getSerialNumber()); Log.d(ActivityHttpClient.LOG_TAG, "Version: " + cert.getVersion()); Log.d(ActivityHttpClient.LOG_TAG, "Not before: " + cert.getNotBefore().toString()); Log.d(ActivityHttpClient.LOG_TAG, "Not after: " + cert.getNotAfter().toString()); Log.d(ActivityHttpClient.LOG_TAG, "---------------------------"); } // Make sure that it hasn't expired. cert.checkValidity(); // Verify the certificate's chain. cert.verify(publicKey); } } catch (InvalidKeyException ex) { error = ex; } catch (NoSuchAlgorithmException ex) { error = ex; } catch (NoSuchProviderException ex) { error = ex; } catch (SignatureException ex) { error = ex; } if (null != error && ActivityHttpClient.isDebugging()) { Log.e(ActivityHttpClient.LOG_TAG, "Error while setting up a secure socket factory.", error); throw new CertificateException(error); } } @Override public X509Certificate[] getAcceptedIssuers() { return acceptedIssuers; } } }, null); setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); }
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 {/*from w w w .j a v a 2 s . co 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; } }
From source file:nu.yona.app.utils.AppUtils.java
public static boolean checkCACertificate() { boolean isCertExist = false; try {/* www .j ava 2s. c o m*/ KeyStore ks = KeyStore.getInstance("AndroidCAStore"); if (ks != null) { ks.load(null, null); Enumeration aliases = ks.aliases(); if (YonaApplication.getEventChangeManager().getDataState().getUser() != null && YonaApplication .getEventChangeManager().getDataState().getUser().getSslRootCertCN() != null) { String caCertName = YonaApplication.getEventChangeManager().getDataState().getUser() .getSslRootCertCN(); if (!TextUtils.isEmpty(caCertName)) { while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); java.security.cert.X509Certificate cert = (java.security.cert.X509Certificate) ks .getCertificate(alias); if (cert.getIssuerDN().getName().contains(caCertName)) { isCertExist = true; break; } } } } } } catch (Exception e) { reportException(AppUtils.class.getSimpleName(), e, Thread.currentThread()); } return isCertExist; }
From source file:ch.cyberduck.core.ssl.CertificateStoreX509KeyManager.java
@Override public String chooseClientAlias(final String[] keyTypes, final Principal[] issuers, final Socket socket) { try {//from www .ja v a 2 s . c o m final X509Certificate selected; final String hostname = socket.getInetAddress().getHostName(); try { final String alias = bookmark.getCredentials().getCertificate(); if (StringUtils.isNotBlank(alias)) { log.info(String.format("Return saved certificate alias %s for host %s", alias, bookmark)); return alias; } selected = callback.choose(keyTypes, issuers, bookmark, MessageFormat.format(LocaleFactory.localizedString( "The server requires a certificate to validate your identity. Select the certificate to authenticate yourself to {0}."), hostname)); } catch (ConnectionCanceledException e) { if (log.isInfoEnabled()) { log.info(String.format("No certificate selected for socket %s", socket)); } return null; } if (null == selected) { if (log.isInfoEnabled()) { log.info(String.format("No certificate selected for socket %s", socket)); } // Disconnect return null; } final String[] aliases = this.getClientAliases(keyTypes, issuers); if (null != aliases) { final KeyStore store; try { store = this.getKeystore(); } catch (IOException e) { return null; } for (String alias : aliases) { if (store.getCertificate(alias).equals(selected)) { if (log.isInfoEnabled()) { log.info(String.format("Selected certificate alias %s for certificate %s", alias, selected)); } bookmark.getCredentials().setCertificate(alias); return alias; } } } log.warn(String.format("No matching alias found for selected certificate %s", selected)); // Return null if there are no matches return null; } catch (KeyStoreException e) { log.error(String.format("Keystore not loaded %s", e.getMessage())); } // Return null if there are no matches return null; }