List of usage examples for java.security KeyStore getInstance
public static KeyStore getInstance(String type) throws KeyStoreException
From source file:com.eviware.soapui.impl.wsdl.support.http.SoapUISSLSocketFactory.java
@Override public Socket createSocket(HttpParams params) throws IOException { String sslConfig = (String) params.getParameter(SoapUIHttpRoute.SOAPUI_SSL_CONFIG); if (StringUtils.isNullOrEmpty(sslConfig)) { return enableSocket((SSLSocket) sslContext.getSocketFactory().createSocket()); }/*from w w w. j av a 2s . c om*/ SSLSocketFactory factory = factoryMap.get(sslConfig); if (factory != null) { if (factory == this) return enableSocket((SSLSocket) sslContext.getSocketFactory().createSocket()); else return enableSocket((SSLSocket) factory.createSocket(params)); } try { // try to create new factory for specified config int ix = sslConfig.lastIndexOf(' '); String keyStore = sslConfig.substring(0, ix); String pwd = sslConfig.substring(ix + 1); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); if (keyStore.trim().length() > 0) { File f = new File(keyStore); if (f.exists()) { log.info("Initializing Keystore from [" + keyStore + "]"); try { KeyMaterial km = new KeyMaterial(f, pwd.toCharArray()); ks = km.getKeyStore(); } catch (Exception e) { SoapUI.logError(e); pwd = null; } } } factory = new SoapUISSLSocketFactory(ks, pwd); factoryMap.put(sslConfig, factory); return enableSocket((SSLSocket) factory.createSocket(params)); } catch (Exception gse) { SoapUI.logError(gse); return enableSocket((SSLSocket) super.createSocket(params)); } }
From source file:io.fabric8.elasticsearch.RequestRunner.java
protected final OkHttpClient getHttpClient() throws Exception { File ksFile = new File(keyStore); KeyStore trusted = KeyStore.getInstance("JKS"); FileInputStream in = new FileInputStream(ksFile); trusted.load(in, password.toCharArray()); in.close();/*from w w w.ja v a 2 s. c om*/ SSLContext sslContext = SSLContext.getInstance("TLS"); TrustManagerFactory trustManagerFactory = InsecureTrustManagerFactory.INSTANCE; X509TrustManager trustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0]; sslContext.init(null, trustManagerFactory.getTrustManagers(), null); OkHttpClient client = new okhttp3.OkHttpClient.Builder() .sslSocketFactory(sslContext.getSocketFactory(), trustManager).readTimeout(1, TimeUnit.MINUTES) .writeTimeout(1, TimeUnit.MINUTES).build(); return client; }
From source file:be.fedict.eid.idp.model.bean.IdentityServiceSingletonBean.java
/** * Load identity keystore/*from ww w .jav a2s. com*/ * * @param idPIdentityConfig * identity configuration * @return private key entry of identity * @throws KeyStoreLoadException * failed to load keystore */ public IdPIdentity loadIdentity(IdPIdentityConfig idPIdentityConfig) throws KeyStoreLoadException { try { if (null == idPIdentityConfig) { throw new KeyStoreLoadException("Identity config is empty!"); } FileInputStream keyStoreInputStream = null; if (idPIdentityConfig.getKeyStoreType().equals(KeyStoreType.PKCS11)) { Security.addProvider(new SunPKCS11(idPIdentityConfig.getKeyStorePath())); } else { try { keyStoreInputStream = new FileInputStream(idPIdentityConfig.getKeyStorePath()); } catch (FileNotFoundException e) { throw new KeyStoreLoadException("Can't load keystore from config-specified location: " + idPIdentityConfig.getKeyStorePath(), e); } } // load keystore KeyStore keyStore = KeyStore.getInstance(idPIdentityConfig.getKeyStoreType().getJavaKeyStoreType()); char[] password; if (null != idPIdentityConfig.getKeyStorePassword() && !idPIdentityConfig.getKeyStorePassword().isEmpty()) { password = idPIdentityConfig.getKeyStorePassword().toCharArray(); } else { password = null; } keyStore.load(keyStoreInputStream, password); // find entry alias Enumeration<String> aliases = keyStore.aliases(); if (!aliases.hasMoreElements()) { throw new KeyStoreLoadException("no keystore aliases present"); } String alias; if (null != idPIdentityConfig.getKeyEntryAlias() && !idPIdentityConfig.getKeyEntryAlias().trim().isEmpty()) { boolean found = false; while (aliases.hasMoreElements()) { if (aliases.nextElement().equals(idPIdentityConfig.getKeyEntryAlias())) { found = true; break; } } if (!found) { throw new KeyStoreLoadException( "no keystore entry with alias \"" + idPIdentityConfig.getKeyEntryAlias() + "\""); } alias = idPIdentityConfig.getKeyEntryAlias(); } else { alias = aliases.nextElement(); } LOG.debug("keystore alias: " + alias); // get keystore entry char[] entryPassword; if (null != idPIdentityConfig.getKeyEntryPassword() && !idPIdentityConfig.getKeyEntryPassword().isEmpty()) { entryPassword = idPIdentityConfig.getKeyEntryPassword().toCharArray(); } else { entryPassword = null; } KeyStore.Entry entry = keyStore.getEntry(alias, new KeyStore.PasswordProtection(entryPassword)); if (!(entry instanceof PrivateKeyEntry)) { throw new KeyStoreLoadException("private key entry expected"); } return new IdPIdentity(idPIdentityConfig.getName(), (PrivateKeyEntry) entry); } catch (KeyStoreException e) { throw new KeyStoreLoadException(e); } catch (CertificateException e) { throw new KeyStoreLoadException(e); } catch (NoSuchAlgorithmException e) { throw new KeyStoreLoadException(e); } catch (UnrecoverableEntryException e) { throw new KeyStoreLoadException(e); } catch (IOException e) { throw new KeyStoreLoadException(e); } }
From source file:eu.eubrazilcc.lvl.core.http.client.TrustedHttpsClient.java
/** * Creates a custom SSL context where clients will trust own CA and self-signed certificates and associates a HTTP client to the context. * @return a HTTP client that will trust own CA and self-signed certificates. * @throws Exception if an error occurs. */// ww w.ja va2 s. com private static final CloseableHttpClient createHttpClient(final File trustStoreDir, final char[] password, final String url) { CloseableHttpClient httpClient = null; try { final File trustStoreFile = new File(trustStoreDir, "trusted.keystore"); final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); // create a new, empty trust store if (!trustStoreFile.exists()) { trustStoreDir.mkdirs(); trustStoreFile.createNewFile(); trustStore.load(null, password); } // import certificate to trust store importCertificate(url, trustStore); // save trust store to disk try (final FileOutputStream outstream = new FileOutputStream(trustStoreFile)) { trustStore.store(outstream, password); } // trust own CA and all self-signed certificates final SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build(); // allow trusted protocols only final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "SSLv2Hello", "TLSv1", "TLSv1.1", "TLSv1.2" }, null, new DefaultHostnameVerifier()); httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); } catch (Exception e) { LOGGER.error("Failed to create HTTP client", e); } return httpClient; }
From source file:com.mhise.util.MHISEUtil.java
public static boolean saveImportedCertificateToDevice(String certificate, String password, Context ctx, String certName) {//from w ww .j a v a2 s . c om 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; }
From source file:com.mindprotectionkit.freephone.signaling.SignalingSocket.java
private Socket constructSSLSocket(Context context, String host, int port) throws SignalingException { try {/*from w w w . j av a2 s .c o m*/ AssetManager assetManager = context.getAssets(); InputStream keyStoreInputStream = assetManager.open("whisper.store"); KeyStore trustStore = KeyStore.getInstance("BKS"); trustStore.load(keyStoreInputStream, "whisper".toCharArray()); SSLSocketFactory sslSocketFactory = new SSLSocketFactory(trustStore); if (Release.SSL) { sslSocketFactory.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); } else { Log.w("SignalingSocket", "Disabling hostname verification..."); sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } return timeoutHackConnect(sslSocketFactory, host, port); } catch (IOException ioe) { throw new SignalingException(ioe); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException(e); } catch (KeyStoreException e) { throw new IllegalArgumentException(e); } catch (CertificateException e) { throw new IllegalArgumentException(e); } catch (KeyManagementException e) { throw new IllegalArgumentException(e); } catch (UnrecoverableKeyException e) { throw new IllegalArgumentException(e); } }
From source file:com.rsmart.kuali.kfs.sys.context.PropertyLoadingFactoryBean.java
/** * Decrypts encrypted values in properties. Interprets that any property in the {@link Properties} instance * provided with a key ending with the {@code ENCRYPTED_PROPERTY_EXTENSION} is considered to be encrypted. * It is then decrypted and replaced with a key of the same name only using the {@code PASSWORD_PROPERTY_EXTENSION} * //from ww w . java2s . com * @param props the {@link Properties} to decrypt * @throws {@link Exception} if there's any problem decrypting/encrypting properties. */ protected void decryptProps(final Properties props) throws Exception { final String keystore = props.getProperty(KEYSTORE_LOCATION_PROPERTY); final String storepass = props.getProperty(KEYSTORE_PASSWORD_PROPERTY); final FileInputStream fs = new FileInputStream(keystore); final KeyStore jks = KeyStore.getInstance(KEYSTORE_TYPE); jks.load(fs, storepass.toCharArray()); fs.close(); final Cipher cipher = Cipher.getInstance(ENCRYPTION_STRATEGY); cipher.init(Cipher.DECRYPT_MODE, (PrivateKey) jks.getKey(RICE_RSA_KEY_NAME, storepass.toCharArray())); for (final String key : props.stringPropertyNames()) { if (key.endsWith(ENCRYPTED_PROPERTY_EXTENSION)) { final String prefix = key.substring(0, key.indexOf(ENCRYPTED_PROPERTY_EXTENSION)); final String encrypted_str = props.getProperty(key); props.setProperty(prefix + PASSWORD_PROPERTY_EXTENSION, new String(cipher.doFinal(new BASE64Decoder().decodeBuffer(encrypted_str)))); } } }
From source file:eu.optimis.trustedinstance.TrustedInstanceImpl.java
private synchronized void initialize() { //storage = new DBStorage(); String keystore = ComponentConfigurationProvider.getString("trusted.instance.keystore"); //$NON-NLS-1$ String password = ComponentConfigurationProvider.getString("trusted.instance.keystore.password"); //$NON-NLS-1$ String alias = ComponentConfigurationProvider.getString("trusted.instance.keystore.alias"); //$NON-NLS-1$ String publicCert = ComponentConfigurationProvider.getString("trusted.instance.keystore.public.cert"); //$NON-NLS-1$ infoServiceName = ComponentConfigurationProvider.getString("trusted.instance.infoservice.client.name"); infoServiceUrl = ComponentConfigurationProvider.getString("trusted.instance.infoservice.client.url"); try {/*ww w .ja v a 2 s . c o m*/ keyStore_input_stream = getClass().getResourceAsStream(keystore); if (keyStore_input_stream == null) { throw new Exception("unable to load keystore of the trusted instance"); } if (password == null) { throw new Exception("unable to load passowrd of the keystore"); } ti_keyStorePass = password.toCharArray(); if (alias == null) { throw new Exception("unable to load alias of the keystore"); } ti_keyStoreAlias = alias; publicCert_input_stream = getClass().getResourceAsStream(publicCert); if (publicCert_input_stream == null) { throw new Exception("unable to load public certificate of the trusted instance"); } CertificateFactory ti_cf = CertificateFactory.getInstance("X.509"); ti_certificate = (X509Certificate) ti_cf.generateCertificate(publicCert_input_stream); ti_ks = KeyStore.getInstance("JKS"); ti_ks.load(keyStore_input_stream, ti_keyStorePass); if (infoServiceName == null) { throw new Exception("unable to find name for ProviderInfoService"); } if (infoServiceUrl == null) { throw new Exception("unable to find URL for ProviderInfoService"); } } catch (Exception e) { System.out.println("ERROR: " + e.getMessage()); } }
From source file:brooklyn.launcher.BrooklynWebServerTest.java
private KeyStore load(String name, String password) throws Exception { KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File(getFile(name))); keystore.load(instream, password.toCharArray()); return keystore; }