List of usage examples for java.security KeyStore aliases
public final Enumeration<String> aliases() throws KeyStoreException
From source file:org.apache.ws.security.components.crypto.Merlin.java
/** * Get an X509 Certificate (chain) of the X500Principal argument in the supplied KeyStore * @param subjectRDN either an X500Principal or a BouncyCastle X509Name instance. * @param store The KeyStore/* w w w . ja va 2 s. c o m*/ * @return an X509 Certificate (chain) * @throws WSSecurityException */ private Certificate[] getCertificates(byte[] thumbprint, KeyStore store, MessageDigest sha) throws WSSecurityException { try { for (Enumeration<String> e = store.aliases(); e.hasMoreElements();) { String alias = e.nextElement(); Certificate cert = null; Certificate[] certs = store.getCertificateChain(alias); if (certs == null || certs.length == 0) { // no cert chain, so lets check if getCertificate gives us a result. cert = store.getCertificate(alias); if (cert == null) { continue; } certs = new Certificate[] { cert }; } else { cert = certs[0]; } if (cert instanceof X509Certificate) { X509Certificate x509cert = (X509Certificate) cert; try { sha.update(x509cert.getEncoded()); } catch (CertificateEncodingException ex) { throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE, "encodeError", null, ex); } byte[] data = sha.digest(); if (Arrays.equals(data, thumbprint)) { return certs; } } } } catch (KeyStoreException e) { throw new WSSecurityException(WSSecurityException.FAILURE, "keystore", null, e); } return new Certificate[] {}; }
From source file:io.atomix.cluster.messaging.impl.NettyMessagingService.java
private void logKeyStore(KeyStore ks, String ksLocation, char[] ksPwd) { if (log.isInfoEnabled()) { log.info("Loaded cluster key store from: {}", ksLocation); try {/*from w w w . j ava 2 s .c o m*/ for (Enumeration<String> e = ks.aliases(); e.hasMoreElements();) { String alias = e.nextElement(); Key key = ks.getKey(alias, ksPwd); Certificate[] certs = ks.getCertificateChain(alias); log.debug("{} -> {}", alias, certs); final byte[] encodedKey; if (certs != null && certs.length > 0) { encodedKey = certs[0].getEncoded(); } else { log.info("Could not find cert chain for {}, using fingerprint of key instead...", alias); encodedKey = key.getEncoded(); } // Compute the certificate's fingerprint (use the key if certificate cannot be found) MessageDigest digest = MessageDigest.getInstance("SHA1"); digest.update(encodedKey); StringJoiner fingerprint = new StringJoiner(":"); for (byte b : digest.digest()) { fingerprint.add(String.format("%02X", b)); } log.info("{} -> {}", alias, fingerprint); } } catch (Exception e) { log.warn("Unable to print contents of key store: {}", ksLocation, e); } } }
From source file:com.tremolosecurity.config.util.UnisonConfigManagerImpl.java
private void initSSL() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, CertificateException, FileNotFoundException, IOException { if (this.getKeyManagerFactory() == null) { return;/*from w w w. ja v a2 s. co m*/ } KeyStore cacerts = KeyStore.getInstance(KeyStore.getDefaultType()); String cacertsPath = System.getProperty("javax.net.ssl.trustStore"); if (cacertsPath == null) { cacertsPath = System.getProperty("java.home") + "/lib/security/cacerts"; } cacerts.load(new FileInputStream(cacertsPath), null); Enumeration<String> enumer = cacerts.aliases(); while (enumer.hasMoreElements()) { String alias = enumer.nextElement(); java.security.cert.Certificate cert = cacerts.getCertificate(alias); this.ks.setCertificateEntry(alias, cert); } SSLContext sslctx = SSLContexts.custom().loadTrustMaterial(this.ks) .loadKeyMaterial(this.ks, this.cfg.getKeyStorePassword().toCharArray()).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslctx, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); PlainConnectionSocketFactory sf = PlainConnectionSocketFactory.getSocketFactory(); httpClientRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", sf) .register("https", sslsf).build(); globalHttpClientConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES) .setRedirectsEnabled(false).setAuthenticationEnabled(false).build(); }
From source file:org.apache.ws.security.components.crypto.Merlin.java
/** * Find the Public Key in a keystore. /*from w w w . j av a 2 s.c o m*/ */ private boolean findPublicKeyInKeyStore(PublicKey publicKey, KeyStore keyStoreToSearch) { if (keyStoreToSearch == null) { return false; } try { for (Enumeration<String> e = keyStoreToSearch.aliases(); e.hasMoreElements();) { String alias = e.nextElement(); Certificate[] certs = keyStoreToSearch.getCertificateChain(alias); Certificate cert; if (certs == null || certs.length == 0) { // no cert chain, so lets check if getCertificate gives us a result. cert = keyStoreToSearch.getCertificate(alias); if (cert == null) { continue; } } else { cert = certs[0]; } if (!(cert instanceof X509Certificate)) { continue; } X509Certificate x509cert = (X509Certificate) cert; if (publicKey.equals(x509cert.getPublicKey())) { return true; } } } catch (KeyStoreException e) { return false; } return false; }
From source file:org.wildfly.security.x500.cert.acme.AcmeClientSpiTest.java
@BeforeClass public static void setUp() throws Exception { mockRetryAfter(); // no need to sleep in between polling attempts during testing KeyStore keyStore = KeyStore.getInstance("jks"); try (InputStream is = AcmeClientSpiTest.class.getResourceAsStream(KEYSTORE)) { keyStore.load(is, KEYSTORE_PASSWORD); }/* w w w. j a v a 2s.c om*/ int numAliases = keyStore.size(); aliasToCertificateMap = new HashMap<>(numAliases); aliasToPrivateKeyMap = new HashMap<>(numAliases); final Enumeration<String> aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); aliasToCertificateMap.put(alias, (X509Certificate) keyStore.getCertificate(alias)); aliasToPrivateKeyMap.put(alias, (PrivateKey) keyStore.getKey(alias, KEYSTORE_PASSWORD)); } server = new ClientAndServer(4001); client = new MockWebServer(); client.start(5002); // this is the port our mock Let's Encrypt server will use to access the client }
From source file:ca.psiphon.PsiphonTunnel.java
private String setupTrustedCertificates(Context context) throws Exception { // Copy the Android system CA store to a local, private cert bundle file. ////from www. j a va2 s.co m // This results in a file that can be passed to SSL_CTX_load_verify_locations // for use with OpenSSL modes in tunnel-core. // https://www.openssl.org/docs/manmaster/ssl/SSL_CTX_load_verify_locations.html // // TODO: to use the path mode of load_verify_locations would require emulating // the filename scheme used by c_rehash: // https://www.openssl.org/docs/manmaster/apps/c_rehash.html // http://stackoverflow.com/questions/19237167/the-new-subject-hash-openssl-algorithm-differs File directory = context.getDir("PsiphonCAStore", Context.MODE_PRIVATE); final String errorMessage = "copy AndroidCAStore failed"; try { File file = new File(directory, "certs.dat"); // Pave a fresh copy on every run, which ensures we're not using old certs. // Note: assumes KeyStore doesn't return revoked certs. // // TODO: this takes under 1 second, but should we avoid repaving every time? file.delete(); PrintStream output = null; try { output = new PrintStream(new FileOutputStream(file)); KeyStore keyStore; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { keyStore = KeyStore.getInstance("AndroidCAStore"); keyStore.load(null, null); } else { keyStore = KeyStore.getInstance("BKS"); FileInputStream inputStream = new FileInputStream("/etc/security/cacerts.bks"); try { keyStore.load(inputStream, "changeit".toCharArray()); } finally { if (inputStream != null) { inputStream.close(); } } } Enumeration<String> aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias); output.println("-----BEGIN CERTIFICATE-----"); String pemCert = new String(Base64.encode(cert.getEncoded(), Base64.NO_WRAP), "UTF-8"); // OpenSSL appears to reject the default linebreaking done by Base64.encode, // so we manually linebreak every 64 characters for (int i = 0; i < pemCert.length(); i += 64) { output.println(pemCert.substring(i, Math.min(i + 64, pemCert.length()))); } output.println("-----END CERTIFICATE-----"); } mHostService.onDiagnosticMessage("prepared PsiphonCAStore"); return file.getAbsolutePath(); } finally { if (output != null) { output.close(); } } } catch (KeyStoreException e) { throw new Exception(errorMessage, e); } catch (NoSuchAlgorithmException e) { throw new Exception(errorMessage, e); } catch (CertificateException e) { throw new Exception(errorMessage, e); } catch (IOException e) { throw new Exception(errorMessage, e); } }
From source file:com.adito.boot.KeyStoreManager.java
/** * Import a key in PKCS12 key format/*from w w w . j a v a2 s . c o m*/ * * @param keyFile file to import * @param password password for key * @param alias alias for key * @param newAlias * @throws Exception on any error * @return the alias of the key imported */ public String importPKCS12Key(File keyFile, String password, String alias, String newAlias) throws Exception { KeyStore kspkcs12 = KeyStore.getInstance("PKCS12"); kspkcs12.load(new FileInputStream(keyFile), password == null ? null : password.toCharArray()); boolean hasTemp = false; if (isKeyStoreEmpty()) { if (isKeyStoreExists()) { deleteKeyStore(); } createKeyStore(); String dname = "cn=tmp, ou=tmp, o=tmp, l=tmp, st=tmp, c=GB"; createKey("temporary-key", dname); hasTemp = true; reloadKeystore(); } try { String firstAlias = (String) kspkcs12.aliases().nextElement(); if (Util.isNullOrTrimmedBlank(alias)) { log.info("Alias not specified, importing first alias " + firstAlias); alias = firstAlias; } if (Util.isNullOrTrimmedBlank(newAlias)) { log.info("New alias not specified, using imported alias " + alias); newAlias = alias; } Certificate c[] = kspkcs12.getCertificateChain(alias); // Make sure we don't have a null chain if (c == null) c = new Certificate[] {}; Key key = kspkcs12.getKey(alias, password == null ? null : password.toCharArray()); if (key == null) { throw new Exception("No alias of '" + alias + "' in imported PKCS12 key file."); } this.keyStore.setKeyEntry(newAlias, key, getKeyStorePassword().toCharArray(), c); } finally { if (hasTemp || keyStore.containsAlias("temporary-key")) this.keyStore.deleteEntry("temporary-key"); OutputStream out = null; try { out = new FileOutputStream(keyStoreFile.getAbsolutePath()); getKeyStore().store(out, getKeyStorePassword().toCharArray()); } finally { Util.closeStream(out); } updateRepository(false); } return newAlias; }
From source file:com.mhise.util.MHISEUtil.java
public static boolean verifyP12StorePassword(String keyStorePath, String password, String serialNumber, Context ctx) {/*from w w w .j av a2s. co m*/ boolean isInstalledCertificateValid = false; KeyStore trustStore = null; FileInputStream fin = null; try { trustStore = KeyStore.getInstance("PKCS12"); } catch (KeyStoreException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } File file = new File(keyStorePath); if (file.exists()) { try { fin = new FileInputStream(file); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { trustStore.load(fin, password.toCharArray()); fin.close(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); MHISEUtil.displayDialog(ctx, "Invalid Password", null); } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); MHISEUtil.displayDialog(ctx, "Invalid Password", null); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); MHISEUtil.displayDialog(ctx, "Invalid Password", null); } Enumeration<String> aliases = null; try { aliases = trustStore.aliases(); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); java.security.cert.X509Certificate cert = null; try { cert = (X509Certificate) trustStore.getCertificate(alias); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (cert.getSerialNumber().toString().equals(serialNumber)) { // isInstalledCertificateValid = true; SharedPreferences sharedPreferences = ctx.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(Constants.KEY_SERIAL_NUMBER, "" + cert.getSerialNumber().toString(16)); editor.commit(); return true; } } } catch (NullPointerException e) { // TODO: handle exception Logger.debug("password invalid", "" + e); } } return isInstalledCertificateValid; }
From source file:com.sun.identity.console.user.model.UMChangeUserPasswordModelImpl.java
public void changePwd(String userId, String oldPassword, String newPassword) throws AMConsoleException { String[] params = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD }; try {/*from www . j a v a 2s .c o m*/ logEvent("ATTEMPT_MODIFY_IDENTITY_ATTRIBUTE_VALUE", params); AMIdentity amIdentity = IdUtils.getIdentity(getUserSSOToken(), userId); boolean verified = verifyOldPassword(amIdentity, userId, oldPassword.toCharArray()); if (!verified) { String strError = "Authorized for password changed denied"; String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError }; logEvent("SSO_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx); throw new AMConsoleException(strError); } Map passwordMap = new AMHashMap(2); Set set = new HashSet(2); set.add(newPassword); passwordMap.put(AMAdminConstants.ATTR_USER_PASSWORD, set); Set<String> attributeNames = new HashSet<String>(); attributeNames.add(USERPKCS12_BINARY_ATTRNAME); Map<String, byte[][]> userPKCS12Map = amIdentity.getBinaryAttributes(attributeNames); if (userPKCS12Map != null && userPKCS12Map.get(USERPKCS12_BINARY_ATTRNAME) != null) { KeyStore keyStore = null; try { keyStore = KeyStore.getInstance(TOLVEN_CREDENTIAL_FORMAT_PKCS12); } catch (Exception e) { String strError = "Could not get an instance of KeyStore to create user KeyStore: " + getErrorString(e); String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError }; logEvent("SSO_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx); throw new AMConsoleException(strError); } byte[][] oldUserPKCS12ByteArrs = (byte[][]) userPKCS12Map.get(USERPKCS12_BINARY_ATTRNAME); byte[] oldUserPKCS12 = oldUserPKCS12ByteArrs[0]; ByteArrayInputStream bais = new ByteArrayInputStream(oldUserPKCS12); try { keyStore.load(bais, oldPassword.toCharArray()); } catch (Exception e) { String strError = "Could not get user KeyStore using old password: " + getErrorString(e); String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError }; logEvent("SSO_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx); throw new AMConsoleException(strError); } ByteArrayOutputStream baos = null; try { String alias = keyStore.aliases().nextElement(); PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, oldPassword.toCharArray()); keyStore.setKeyEntry(alias, privateKey, newPassword.toCharArray(), keyStore.getCertificateChain(alias)); baos = new ByteArrayOutputStream(); } catch (Exception e) { String strError = "Could not get Key from user KeyStore: " + getErrorString(e); String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError }; logEvent("SSO_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx); throw new AMConsoleException(strError); } try { keyStore.store(baos, newPassword.toCharArray()); } catch (Exception e) { String strError = "Could not save user KeyStore: " + getErrorString(e); String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError }; logEvent("SSO_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx); throw new AMConsoleException(strError); } byte[] newUserPKCS12 = baos.toByteArray(); byte[][] newUserPKCS12ByteArrs = new byte[1][]; newUserPKCS12ByteArrs[0] = newUserPKCS12; Map<String, byte[][]> newUserPKCS12Map = newUserPKCS12Map = new HashMap<String, byte[][]>(); newUserPKCS12Map.put(USERPKCS12_BINARY_ATTRNAME, newUserPKCS12ByteArrs); // Ensure that the following two lines are never out of sync (one would expect store() to be a transaction) amIdentity.setBinaryAttributes(newUserPKCS12Map); amIdentity.setAttributes(passwordMap); amIdentity.store(); } else { amIdentity.setAttributes(passwordMap); amIdentity.store(); } logEvent("SUCCEED_MODIFY_IDENTITY_ATTRIBUTE_VALUE", params); } catch (SSOException e) { String strError = getErrorString(e); String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError }; logEvent("SSO_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx); throw new AMConsoleException(strError); } catch (IdRepoException e) { String strError = getErrorString(e); String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError }; logEvent("IDM_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx); throw new AMConsoleException(strError); } }