List of usage examples for java.security KeyStore aliases
public final Enumeration<String> aliases() throws KeyStoreException
From source file:org.tolven.config.model.CredentialManager.java
public void changeGroupCredentialPassword(PasswordInfo passwordInfo, char[] oldPassword, char[] newPassword) throws IOException, GeneralSecurityException { if (oldPassword == null) throw new RuntimeException("Old password '" + passwordInfo.getRefId() + "' is null"); if (!getPasswordHolder().verify(passwordInfo, oldPassword)) throw new RuntimeException("Old Password is invalid for '" + passwordInfo.getRefId() + "'"); if (newPassword == null) throw new RuntimeException("New password '" + passwordInfo.getRefId() + "' is null"); CertificateGroupDetail certGroup = getTolvenConfigWrapper().getCredentialGroup(passwordInfo.getRefId()); CertificateKeyDetail keyDetail = certGroup.getKey(); PrivateKey privateKey = getPrivateKey(keyDetail, oldPassword); File keyFile = new File(keyDetail.getSource()); KeyStore keyStore = null; File keyStoreFile = null;/*from w w w . j ava2s. c o m*/ CertificateKeyStoreDetail certKeyStoreDetail = certGroup.getKeyStore(); if (certKeyStoreDetail != null) { keyStore = getTolvenConfigWrapper().getKeyStore(oldPassword, certKeyStoreDetail); keyStoreFile = new File(certKeyStoreDetail.getSource()); } TrustStoreDetail trustStoreDetail = getTolvenConfigWrapper().getTrustStoreDetail(passwordInfo.getRefId()); KeyStore trustStore = null; File trustStoreFile = null; if (trustStore != null) { trustStore = getTolvenConfigWrapper().getTrustStore(oldPassword, trustStoreDetail); trustStoreFile = new File(trustStoreDetail.getSource()); } File tmpKey = null; File tmpKeyStore = null; File tmpTrustStore = null; boolean success = false; try { getTolvenConfigWrapper().getBuildDir().mkdirs(); tmpKey = new File(getTolvenConfigWrapper().getBuildDir(), keyFile.getName()); write(privateKey, keyDetail.getFormat(), tmpKey, newPassword); if (keyStoreFile != null) { tmpKeyStore = new File(getTolvenConfigWrapper().getBuildDir(), keyStoreFile.getName()); String alias = keyStore.aliases().nextElement(); Key key = keyStore.getKey(alias, oldPassword); Certificate[] chain = keyStore.getCertificateChain(alias); keyStore.setKeyEntry(alias, key, newPassword, chain); write(keyStore, tmpKeyStore, newPassword); } if (trustStoreFile != null) { tmpTrustStore = new File(getTolvenConfigWrapper().getBuildDir(), trustStoreFile.getName()); write(trustStore, tmpTrustStore, newPassword); } FileUtils.copyFile(tmpKey, keyFile); if (keyStoreFile != null) { FileUtils.copyFile(tmpKeyStore, keyStoreFile); } if (trustStoreFile != null) { FileUtils.copyFile(tmpTrustStore, trustStoreFile); } success = true; } finally { if (success) { if (tmpKey != null) { tmpKey.delete(); } if (tmpKeyStore != null) { tmpKeyStore.delete(); } if (tmpKeyStore != null) { tmpKeyStore.delete(); } getPasswordHolder().changePassword(passwordInfo, oldPassword, newPassword); } } }
From source file:org.kuali.mobility.push.dao.PushDaoImpl.java
private SSLSocket openConnectionToAPNS(String host, int port, String key, String passphrase) { SSLSocket socket;//from w w w . j a v a 2 s.c om try { KeyStore keyStore = KeyStore.getInstance("PKCS12"); // keyStore.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("newcert.p12"), "strange word to use".toCharArray()); // keyStore.load(getClass().getResourceAsStream("/newcert.p12"), "strange word to use".toCharArray()); // keyStore.load(this.getClass().getClassLoader().getResourceAsStream("newcert.p12"), "strange word to use".toCharArray()); // This works when built with Eclipse, but not when built from command line. // Has to do with where the build system puts /resources/*.p12 file // keyStore.load(this.getClass().getClassLoader().getResourceAsStream(key), "strange word to use".toCharArray()); // Currently only works when read from the server's FS. Won't currently read from within eclipse project. // Putting it in /opt/kme/push prevents naming conflicts. keyStore.load(new FileInputStream("/opt/kme/push/newcert.p12"), "strange word to use".toCharArray()); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("sunx509"); keyManagerFactory.init(keyStore, "strange word to use".toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("sunx509"); trustManagerFactory.init(keyStore); SSLContext sslCtx = SSLContext.getInstance("TLS"); sslCtx.init(keyManagerFactory.getKeyManagers(), null, null); SSLSocketFactory sslSocketFactory = sslCtx.getSocketFactory(); socket = (SSLSocket) sslSocketFactory.createSocket(host, port); socket.startHandshake(); //Diagnostic output Enumeration e = keyStore.aliases(); LOG.info(e.toString()); while (e.hasMoreElements()) { LOG.info("Alias: " + e.nextElement().toString()); } String not = (socket.isConnected()) ? "" : "NOT "; LOG.info("SSLSocket is " + not + "Connected"); LOG.info("Connected to: " + socket.getInetAddress().getCanonicalHostName()); LOG.info("Connected to: " + socket.getInetAddress().getHostAddress()); String cs[] = socket.getEnabledCipherSuites(); LOG.info("CipherSuites: " + Arrays.toString(cs)); String ep[] = socket.getEnabledProtocols(); LOG.info("Enabled Protocols: " + Arrays.toString(ep)); LOG.info("Timeout: " + socket.getSoTimeout()); LOG.info("Send Buffer Size: " + socket.getSendBufferSize()); return socket; } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:org.lockss.protocol.BlockingStreamComm.java
private void logKeyStore(KeyStore ks, char[] privateKeyPassWord) { log.debug3("start of key store"); try {/*from www . j ava 2s . c o m*/ for (Enumeration en = ks.aliases(); en.hasMoreElements();) { String alias = (String) en.nextElement(); log.debug3("Next alias " + alias); if (ks.isCertificateEntry(alias)) { log.debug3("About to Certificate"); java.security.cert.Certificate cert = ks.getCertificate(alias); if (cert == null) { log.debug3(alias + " null cert chain"); } else { log.debug3("Cert for " + alias + " is " + cert.toString()); } } else if (ks.isKeyEntry(alias)) { log.debug3("About to getKey"); Key privateKey = ks.getKey(alias, privateKeyPassWord); log.debug3(alias + " key " + privateKey.getAlgorithm() + "/" + privateKey.getFormat()); } else { log.debug3(alias + " neither key nor cert"); } } log.debug3("end of key store"); } catch (Exception ex) { log.error("logKeyStore() threw " + ex); } }
From source file:org.wso2.carbon.security.keystore.KeyStoreAdmin.java
/** * This method will list 1. Certificate aliases 2. Private key alise 3. Private key value to a * given keystore./*from w w w .j a v a 2 s .com*/ * * @param keyStoreName The name of the keystore * @return Instance of KeyStoreData * @throws SecurityConfigException will be thrown */ public KeyStoreData getKeystoreInfo(String keyStoreName) throws SecurityConfigException { try { if (keyStoreName == null) { throw new Exception("keystore name cannot be null"); } KeyStore keyStore; String keyStoreType; String privateKeyPassowrd = null; if (KeyStoreUtil.isPrimaryStore(keyStoreName)) { KeyStoreManager keyMan = KeyStoreManager.getInstance(tenantId); keyStore = keyMan.getPrimaryKeyStore(); ServerConfiguration serverConfig = ServerConfiguration.getInstance(); keyStoreType = serverConfig .getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIMARY_KEYSTORE_TYPE); privateKeyPassowrd = serverConfig .getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIVATE_KEY_PASSWORD); } else { String path = SecurityConstants.KEY_STORES + "/" + keyStoreName; if (!registry.resourceExists(path)) { throw new SecurityConfigException("Key Store not found"); } Resource resource = registry.get(path); KeyStoreManager manager = KeyStoreManager.getInstance(tenantId); keyStore = manager.getKeyStore(keyStoreName); keyStoreType = resource.getProperty(SecurityConstants.PROP_TYPE); String encpass = resource.getProperty(SecurityConstants.PROP_PRIVATE_KEY_PASS); if (encpass != null) { CryptoUtil util = CryptoUtil.getDefaultCryptoUtil(); privateKeyPassowrd = new String(util.base64DecodeAndDecrypt(encpass)); } } // Fill the information about the certificates Enumeration<String> aliases = keyStore.aliases(); List<org.wso2.carbon.security.keystore.service.CertData> certDataList = new ArrayList<>(); Format formatter = new SimpleDateFormat("dd/MM/yyyy"); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (keyStore.isCertificateEntry(alias)) { X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias); certDataList.add(fillCertData(cert, alias, formatter)); } } // Create a cert array CertData[] certs = certDataList.toArray(new CertData[certDataList.size()]); // Create a KeyStoreData bean, set the name and fill in the cert information KeyStoreData keyStoreData = new KeyStoreData(); keyStoreData.setKeyStoreName(keyStoreName); keyStoreData.setCerts(certs); keyStoreData.setKeyStoreType(keyStoreType); aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); // There be only one entry in WSAS related keystores if (keyStore.isKeyEntry(alias)) { X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias); keyStoreData.setKey(fillCertData(cert, alias, formatter)); PrivateKey key = (PrivateKey) keyStore.getKey(alias, privateKeyPassowrd.toCharArray()); String pemKey; pemKey = "-----BEGIN PRIVATE KEY-----\n"; pemKey += Base64.encode(key.getEncoded()); pemKey += "\n-----END PRIVATE KEY-----"; keyStoreData.setKeyValue(pemKey); break; } } return keyStoreData; } catch (Exception e) { String msg = "Error has encounted while loading the keystore to the given keystore name " + keyStoreName; log.error(msg, e); throw new SecurityConfigException(msg); } }
From source file:org.wso2.carbon.security.keystore.KeyStoreAdmin.java
/** * This method will list 1. Certificate aliases 2. Private key alise 3. Private key value to a * given keystore./*w w w.j a v a 2 s .co m*/ * * @param keyStoreName The name of the keystore * @param pageNumber page number * @return Instance of KeyStoreData * @throws SecurityConfigException will be thrown */ public PaginatedKeyStoreData getPaginatedKeystoreInfo(String keyStoreName, int pageNumber) throws SecurityConfigException { try { if (keyStoreName == null) { throw new Exception("keystore name cannot be null"); } KeyStore keyStore; String keyStoreType; String privateKeyPassowrd = null; if (KeyStoreUtil.isPrimaryStore(keyStoreName)) { KeyStoreManager keyMan = KeyStoreManager.getInstance(tenantId); keyStore = keyMan.getPrimaryKeyStore(); ServerConfiguration serverConfig = ServerConfiguration.getInstance(); keyStoreType = serverConfig .getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIMARY_KEYSTORE_TYPE); privateKeyPassowrd = serverConfig .getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIVATE_KEY_PASSWORD); } else { String path = SecurityConstants.KEY_STORES + "/" + keyStoreName; if (!registry.resourceExists(path)) { throw new SecurityConfigException("Key Store not found"); } Resource resource = registry.get(path); KeyStoreManager manager = KeyStoreManager.getInstance(tenantId); keyStore = manager.getKeyStore(keyStoreName); keyStoreType = resource.getProperty(SecurityConstants.PROP_TYPE); String encpass = resource.getProperty(SecurityConstants.PROP_PRIVATE_KEY_PASS); if (encpass != null) { CryptoUtil util = CryptoUtil.getDefaultCryptoUtil(); privateKeyPassowrd = new String(util.base64DecodeAndDecrypt(encpass)); } } // Fill the information about the certificates Enumeration<String> aliases = keyStore.aliases(); List<org.wso2.carbon.security.keystore.service.CertData> certDataList = new ArrayList<>(); Format formatter = new SimpleDateFormat("dd/MM/yyyy"); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (keyStore.isCertificateEntry(alias)) { X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias); certDataList.add(fillCertData(cert, alias, formatter)); } } // Create a cert array CertData[] certs = certDataList.toArray(new CertData[certDataList.size()]); // Create a KeyStoreData bean, set the name and fill in the cert information PaginatedKeyStoreData keyStoreData = new PaginatedKeyStoreData(); keyStoreData.setKeyStoreName(keyStoreName); keyStoreData.setPaginatedCertData(doPaging(pageNumber, certs)); keyStoreData.setKeyStoreType(keyStoreType); aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); // There be only one entry in WSAS related keystores if (keyStore.isKeyEntry(alias)) { X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias); keyStoreData.setKey(fillCertData(cert, alias, formatter)); PrivateKey key = (PrivateKey) keyStore.getKey(alias, privateKeyPassowrd.toCharArray()); String pemKey; pemKey = "-----BEGIN PRIVATE KEY-----\n"; pemKey += Base64.encode(key.getEncoded()); pemKey += "\n-----END PRIVATE KEY-----"; keyStoreData.setKeyValue(pemKey); break; } } return keyStoreData; } catch (Exception e) { String msg = "Error has encounted while loading the keystore to the given keystore name " + keyStoreName; log.error(msg, e); throw new SecurityConfigException(msg); } }
From source file:org.wso2.developerstudio.eclipse.qos.project.ui.dashboard.QoSDashboardPage.java
private void readKeyStore() { try {//ww w . j av a 2s .c om KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); String filePath = preferenceStore.getString("org.wso2.developerstudio.eclipse.platform.ui", ClientTrustStorePreferencePage.TRUST_STORE_LOCATION, null, null); String password = preferenceStore.getString("org.wso2.developerstudio.eclipse.platform.ui", ClientTrustStorePreferencePage.TRUST_STORE_PASSWORD, null, null); //Fixing TOOLS-2272 - checked filePath and password for null if (filePath != null && password != null) { keyStore.load(new FileInputStream(new File(filePath)), password.toCharArray()); String[] split = filePath.split(File.separator); String alis = null; Enumeration<String> aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { alis = (String) aliases.nextElement(); break; } keyStoreMap.put(split[split.length - 1], alis); } } catch (Exception e) { log.error("Custom Key-store not found", e); } }
From source file:org.cesecore.certificates.ocsp.OcspResponseGeneratorSessionBean.java
/** Create InternalKeyBindings for Ocsp signing and SSL client authentication certs during ad-hoc upgrades. */ @Deprecated //Remove this method as soon as upgrading from 5->6 is dropped private void createInternalKeyBindings(AuthenticationToken authenticationToken, int cryptoTokenId, KeyStore keyStore, List<InternalKeyBindingTrustEntry> trustDefaults) throws KeyStoreException, CryptoTokenOfflineException, InternalKeyBindingNameInUseException, AuthorizationDeniedException, CertificateEncodingException, CertificateImportException, InvalidAlgorithmException { final Enumeration<String> aliases = keyStore.aliases(); boolean noAliases = true; while (aliases.hasMoreElements()) { final String keyPairAlias = aliases.nextElement(); noAliases = false;/*from ww w.j a va 2s. co m*/ log.info("Found alias " + keyPairAlias + ", trying to figure out if this is something we should convert into a new KeyBinding..."); final Certificate[] chain = keyStore.getCertificateChain(keyPairAlias); if (chain == null || chain.length == 0) { log.info("Alias " + keyPairAlias + " does not contain any certificate and will be ignored."); continue; // Ignore entry } // Extract the default signature algorithm final String signatureAlgorithm = getSigningAlgFromAlgSelection( OcspConfiguration.getSignatureAlgorithm(), chain[0].getPublicKey()); if (OcspKeyBinding.isOcspSigningCertificate(chain[0])) { // Create the actual OcspKeyBinding log.info("Alias " + keyPairAlias + " contains an OCSP certificate and will be converted to an OcspKeyBinding."); int internalKeyBindingId = internalKeyBindingMgmtSession.createInternalKeyBinding( authenticationToken, OcspKeyBinding.IMPLEMENTATION_ALIAS, "OcspKeyBinding for " + keyPairAlias, InternalKeyBindingStatus.DISABLED, null, cryptoTokenId, keyPairAlias, signatureAlgorithm, getOcspKeyBindingDefaultProperties(), trustDefaults); internalKeyBindingMgmtSession.importCertificateForInternalKeyBinding(authenticationToken, internalKeyBindingId, chain[0].getEncoded()); internalKeyBindingMgmtSession.setStatus(authenticationToken, internalKeyBindingId, InternalKeyBindingStatus.ACTIVE); } else if (AuthenticationKeyBinding.isClientSSLCertificate(chain[0])) { log.info("Alias " + keyPairAlias + " contains an SSL client certificate and will be converted to an AuthenticationKeyBinding."); // We are looking for an SSL cert, use this to create an AuthenticationKeyBinding int internalKeyBindingId = internalKeyBindingMgmtSession.createInternalKeyBinding( authenticationToken, AuthenticationKeyBinding.IMPLEMENTATION_ALIAS, "AuthenticationKeyBinding for " + keyPairAlias, InternalKeyBindingStatus.DISABLED, null, cryptoTokenId, keyPairAlias, signatureAlgorithm, null, null); internalKeyBindingMgmtSession.importCertificateForInternalKeyBinding(authenticationToken, internalKeyBindingId, chain[0].getEncoded()); internalKeyBindingMgmtSession.setStatus(authenticationToken, internalKeyBindingId, InternalKeyBindingStatus.ACTIVE); } else { log.info("Alias " + keyPairAlias + " contains certificate of unknown type and will be ignored."); } } if (noAliases) { log.info("No aliases to process were found in the key store."); } }
From source file:org.cesecore.certificates.ocsp.OcspResponseGeneratorSessionBean.java
/** Creates a PKCS#12 KeyStore with keys only from an JKS file (no issuer certs or trusted certs) */ @Deprecated //Remove this method as soon as upgrading from 5->6 is dropped private KeyStore makeKeysOnlyP12(KeyStore keyStore, char[] password) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException, NoSuchProviderException, CertificateException, IOException { final KeyStore p12 = KeyStore.getInstance("PKCS12", "BC"); final KeyStore.ProtectionParameter protParam = (password != null ? new KeyStore.PasswordProtection(password) : null);/* w ww . j a v a 2 s . c o m*/ p12.load(null, password); // initialize final Enumeration<String> en = keyStore.aliases(); while (en.hasMoreElements()) { final String alias = en.nextElement(); if (!keyStore.isKeyEntry(alias)) continue; try { KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, protParam); Certificate[] chain = new Certificate[] { entry.getCertificate() }; p12.setKeyEntry(alias, entry.getPrivateKey(), password, chain); } catch (UnsupportedOperationException uoe) { KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, null); Certificate[] chain = new Certificate[] { entry.getCertificate() }; p12.setKeyEntry(alias, entry.getPrivateKey(), null, chain); } } return p12; }
From source file:com.mhise.util.MHISEUtil.java
public static boolean saveImportedCertificateToDevice(String certificate, String password, Context ctx, String certName) {/*from w w w .j a va2 s. c o m*/ boolean isPasswordCorrect = false; byte[] certificatebytes = null; try { certificatebytes = Base64.decode(certificate, Base64.DEFAULT); } catch (IllegalArgumentException e) { // TODO: handle exception Logger.debug("MHISEUtil-->saveImportedCertificateToDevice", "" + e); } KeyStore localTrustStore = null; try { localTrustStore = KeyStore.getInstance("PKCS12"); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } InputStream is = new ByteArrayInputStream(certificatebytes); try { localTrustStore.load(is, password.toCharArray()); isPasswordCorrect = true; } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } OutputStream fos = null; try { //<<<<<<< .mine //SharedPreferences sharedPreferences = ctx.getSharedPreferences(Constants.PREFS_NAME,Context.MODE_PRIVATE); //String storeName =sharedPreferences.getString(Constants.KEY_CERT_NAME, null); File _mobiusDirectory = new File(Constants.defaultP12StorePath); if (!_mobiusDirectory.exists()) { _mobiusDirectory.mkdir(); } File file = new File(Constants.defaultP12StorePath + certName); fos = new FileOutputStream(file); //fos = ctx.openFileOutput(Constants.defaultP12StoreName, Context.MODE_PRIVATE); localTrustStore.store(fos, MHISEUtil.getStrongPassword(certName).toCharArray()); /*//======= //SharedPreferences sharedPreferences = ctx.getSharedPreferences(Constants.PREFS_NAME,Context.MODE_PRIVATE); //String storeName =sharedPreferences.getString(Constants.KEY_CERT_NAME, null); File file = new File(Constants.defaultP12StorePath+certName); fos = new FileOutputStream(file); //fos = ctx.openFileOutput(Constants.defaultP12StoreName, Context.MODE_PRIVATE); localTrustStore.store(fos,MHISEUtil.getStrongPassword(certName).toCharArray()); >>>>>>> .r4477*/ fos.close(); Enumeration<String> aliases = null; try { aliases = localTrustStore.aliases(); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } //boolean isInstalledCertificateValid = false; while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); java.security.cert.X509Certificate cert = null; try { cert = (X509Certificate) localTrustStore.getCertificate(alias); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } SharedPreferences sharedPreferences1 = ctx.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences1.edit(); Log.i("Imported certificate serial number", "" + cert.getSerialNumber().toString(16)); editor.putString(Constants.KEY_SERIAL_NUMBER, "" + cert.getSerialNumber().toString(16)); editor.commit(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return isPasswordCorrect; }