List of usage examples for java.security KeyStore getInstance
public static KeyStore getInstance(String type) throws KeyStoreException
From source file:com.emc.ecs.sync.filter.EncryptionFilter.java
@Override public void configure(SyncSource source, Iterator<SyncFilter> filters, SyncTarget target) { if (keyAlias == null) throw new ConfigurationException("Must specify the master key alias"); try {//from w w w . java 2s . c o m if (keystore == null) { if (keystoreFile == null) throw new ConfigurationException("Must specify a keystore"); // Init keystore keystore = KeyStore.getInstance("jks"); keystore.load(new FileInputStream(keystoreFile), keystorePass.toCharArray()); log.info("Keystore Loaded"); } transformFactory = new KeyStoreEncryptionFactory(keystore, keyAlias, keystorePass.toCharArray()); // check if we have an unlimited strength policy available if (EncryptionTransformFactory.getMaxKeySize(TransformConstants.DEFAULT_ENCRYPTION_TRANSFORM) >= 256) { log.info("using 256-bit cipher strength"); transformFactory.setEncryptionSettings(TransformConstants.DEFAULT_ENCRYPTION_TRANSFORM, 256, null); } else { if (forceStrong) throw new ConfigurationException("strong encryption is not available"); log.warn("high-strength encryption is unavailable; defaulting to 128-bit"); } } catch (ConfigurationException e) { throw e; } catch (Exception e) { throw new ConfigurationException(e); } }
From source file:learn.encryption.ssl.SSLContext_Https.java
/** * @description javaSSLContext// w w w . j av a2s . c o m * @description https?, SSLContext (NoHttp?SecureRandombug) * @description client.ks?server * @description ?? * @description ????getSSLContext2() */ //@SuppressLint("TrulyRandom") public static SSLContext getSSLContext() { SSLContext sslContext = null; try { sslContext = SSLContext.getInstance("TLS"); // ??, ??assets InputStream inputStream = new FileInputStream(new File("D:\\tomcatcert\\server.ks")); //App.getInstance().getAssets().open("srca.cer"); // ?? CertificateFactory cerFactory = CertificateFactory.getInstance("X.509"); // ?KeyStore KeyStore keyStore = KeyStore.getInstance("jks"); keyStore.load(inputStream, "123456".toCharArray()); //Certificate cer = cerFactory.generateCertificate(inputStream); Certificate cer = keyStore.getCertificate("clientKey"); keyStore.setCertificateEntry("trust", cer); // KeyStorekeyManagerFactory KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, "123456".toCharArray()); // KeyStoreTrustManagerFactory TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); // ?SSLContext sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom()); } catch (Exception e) { e.printStackTrace(); } return sslContext; }
From source file:jenkins.plugins.publish_over_ftp.BapFtpHostConfiguration.java
public FTPClient createFTPClient() throws GeneralSecurityException, FileNotFoundException, IOException { if (useFtpOverTls) { FTPSClient c = new FTPSClient(false); KeyStore ts = KeyStore.getInstance(KeyStore.getDefaultType()); String trustStorePath = System.getProperty("javax.net.ssl.trustStore"); if (trustStorePath != null) { String trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword"); if (trustStorePassword != null) { ts.load(new FileInputStream(trustStorePath), trustStorePassword.toCharArray()); } else { ts.load(new FileInputStream(trustStorePath), null); }//from ww w . j av a2s . c o m } else { ts.load(null); } if (trustedCertificate != null) { InputStream certStream = new ByteArrayInputStream(trustedCertificate.getBytes()); X509Certificate x509certificate = (X509Certificate) CertificateFactory.getInstance("X.509") .generateCertificate(certStream); ts.setCertificateEntry(x509certificate.getSubjectDN().getName(), x509certificate); } c.setTrustManager(TrustManagerUtils.getDefaultTrustManager(ts)); return c; } return new FTPClient(); }
From source file:com.eviware.soapui.impl.wsdl.support.wss.crypto.KeyMaterialWssCrypto.java
public KeyStore load() throws Exception { if (keyStore != null) return keyStore; try {/*w w w . ja va2 s.co m*/ UISupport.setHourglassCursor(); String crypotFilePath = sourceProperty.expand(); String fileExtension = Files.getFileExtension(crypotFilePath); String keystoreType = fileExtensionToKeystoreType(fileExtension); ClassLoader loader = Loader.getClassLoader(KeyMaterialWssCrypto.class); InputStream input = Merlin.loadInputStream(loader, crypotFilePath); keyStore = KeyStore.getInstance(keystoreType); keyStore.load(input, getPassword().toCharArray()); return keyStore; } catch (Exception exceptionFromNormalLoad) { log.warn("Using fallback method to load keystore/truststore due to: " + exceptionFromNormalLoad.getMessage()); try { keyStore = fallbackLoad(); return keyStore; } catch (Exception exceptionFromFallbackLoad) { keyStore = null; SoapUI.logError(exceptionFromFallbackLoad, "Could not load keystore/truststore"); throw new Exception(exceptionFromFallbackLoad); } } finally { UISupport.resetCursor(); } }
From source file:com.archivas.clienttools.arcutils.utils.net.GetCertsX509TrustManager.java
public void initPersistedTrustManager(boolean forcereload) throws NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException { if (persistedTrustManager != null && !forcereload) { return;// ww w .j av a 2 s .c o m } String homedir = System.getProperty("user.home"); String fileNameTemplate = ConfigurationHelper.USER_CONFIG_DIRECTORY + ConfigurationHelper.getStringProperty("ssl.keystore.filename", "cacerts"); String fileName = MessageFormat.format(fileNameTemplate, homedir); persistedKeystoreFile = new File(fileName); try { persistedKeyStore = KeyStore.getInstance("JKS"); try { FileInputStream fis = null; if (persistedKeystoreFile.exists()) { fis = new FileInputStream(persistedKeystoreFile); } persistedKeyStore.load(fis, persistedKeystorePassword); } catch (FileNotFoundException e) { // Don't Care. Go on. LOG.log(Level.WARNING, "Unexpected Exception", e); } catch (IOException e) { LOG.log(Level.WARNING, "Unexpected Exception", e); } catch (CertificateException e) { LOG.log(Level.WARNING, "Unexpected Exception", e); } TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(persistedKeyStore); TrustManager tms[] = tmf.getTrustManagers(); // Iterate over the returned trustmanagers, look for an instance of X509TrustManager. // If found, use that as our "default" trust manager. for (int i = 0; i < tms.length; i++) { if (tms[i] instanceof X509TrustManager) { persistedTrustManager = (X509TrustManager) tms[i]; break; } } LOG.log(Level.FINER, "persistedTrustManager=" + persistedTrustManager); } catch (KeyStoreException e) { LOG.log(Level.WARNING, "Unexpected Exception", e); throw e; } catch (NoSuchAlgorithmException e) { LOG.log(Level.WARNING, "Unexpected Exception", e); throw e; } catch (RuntimeException e) { LOG.log(Level.WARNING, "Unexpected Exception", e); throw e; } }
From source file:it.govpay.core.utils.client.BasicClient.java
private BasicClient(String bundleKey, Connettore connettore) throws ClientException { if (connettore == null) { throw new ClientException("Connettore non configurato"); }//from w w w .j a va 2 s. c o m try { this.url = new URL(connettore.getUrl()); } catch (Exception e) { throw new ClientException("La URL del connettore " + errMsg + " non e' valida: " + e); } sslContext = sslContexts.get(bundleKey); if (connettore.getTipoAutenticazione().equals(EnumAuthType.SSL)) { isSslEnabled = true; if (sslContext == null) { try { FileInputStream finKeyStore = null; FileInputStream finTrustStore = null; KeyManager[] km = null; TrustManager[] tm = null; // Autenticazione CLIENT if (connettore.getTipoSsl().equals(EnumSslType.CLIENT)) { if (connettore.getSslKsType() == null || connettore.getSslKsLocation() == null || connettore.getSslKsPasswd() == null || connettore.getSslPKeyPasswd() == null) throw new ClientException( "Configurazione SSL Client del connettore " + errMsg + " incompleta."); KeyStore keystore = KeyStore.getInstance(connettore.getSslKsType()); // JKS,PKCS12,jceks,bks,uber,gkr finKeyStore = new FileInputStream(connettore.getSslKsLocation()); keystore.load(finKeyStore, connettore.getSslKsPasswd().toCharArray()); KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keystore, connettore.getSslPKeyPasswd().toCharArray()); km = keyManagerFactory.getKeyManagers(); } if (connettore.getSslTsType() == null || connettore.getSslTsLocation() == null || connettore.getSslTsPasswd() == null || connettore.getSslType() == null) throw new ClientException( "Configurazione SSL Server del connettore " + errMsg + " incompleta."); // Autenticazione SERVER KeyStore truststore = KeyStore.getInstance(connettore.getSslTsType()); // JKS,PKCS12,jceks,bks,uber,gkr finTrustStore = new FileInputStream(connettore.getSslTsLocation()); truststore.load(finTrustStore, connettore.getSslTsPasswd().toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(truststore); tm = trustManagerFactory.getTrustManagers(); // Creo contesto SSL sslContext = SSLContext.getInstance(connettore.getSslType()); sslContext.init(km, tm, null); sslContexts.put(bundleKey, sslContext); } catch (Exception e) { throw new ClientException(e); } } } if (connettore.getTipoAutenticazione().equals(EnumAuthType.HTTPBasic)) { ishttpBasicEnabled = true; httpBasicUser = connettore.getHttpUser(); httpBasicPassword = connettore.getHttpPassw(); } }
From source file:com.linkedin.pinot.common.utils.ClientSSLContextGenerator.java
private KeyManager[] setupKeyManagers() { if (_keyStoreFile == null) { return null; }//from www. ja v a2 s . c om try { KeyStore keyStore = KeyStore.getInstance(KEYSTORE_TYPE); LOGGER.info("Setting up keystore with file {}", _keyStoreFile); keyStore.load(new FileInputStream(new File(_keyStoreFile)), _keyStorePassword.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEYMANAGER_FACTORY_ALGORITHM); kmf.init(keyStore, _keyStorePassword.toCharArray()); LOGGER.info("Successfully initialized keystore"); return kmf.getKeyManagers(); } catch (Exception e) { Utils.rethrowException(e); } return null; }
From source file:com.twinsoft.convertigo.engine.MySSLSocketFactory.java
private SSLContext createEasySSLContext() throws NoSuchProviderException, NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException, KeyStoreException, CertificateException, IOException { Engine.logCertificateManager.debug("(MySSLSocketFactory) Creating SSL context"); String algorithm = KeyManagerFactory.getDefaultAlgorithm(); Engine.logCertificateManager.debug("(MySSLSocketFactory) Using KeyManager algorithm " + algorithm); KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm); String keyStoreType = keyStore.endsWith(".pkcs11") ? "pkcs11" : "pkcs12"; Engine.logCertificateManager.debug("(MySSLSocketFactory) Key store type: " + keyStoreType); String alias = null;//from ww w. j av a 2 s. c om KeyStore ks, ts; char[] passPhrase; if (keyStore.equals("") || (keyStore.endsWith(".udv"))) { ks = KeyStore.getInstance(keyStoreType); ks.load(null, keyStorePassword.toCharArray()); kmf.init(ks, null); } else { File file = new File(keyStore); Properties properties = new Properties(); properties.load( new FileInputStream(Engine.CERTIFICATES_PATH + CertificateManager.STORES_PROPERTIES_FILE_NAME)); String p = properties.getProperty(file.getName(), ""); int i = p.indexOf('/'); if (i != -1) { alias = p.substring(i + 1); } if (keyStoreType.equals("pkcs11")) { String providerName = file.getName(); providerName = "SunPKCS11-" + providerName.substring(0, providerName.lastIndexOf('.')); Engine.logCertificateManager.debug("(MySSLSocketFactory) Provider name: '" + providerName + "'"); String pinCode; if (i == -1) { pinCode = Crypto2.decodeFromHexString(p); } else { pinCode = Crypto2.decodeFromHexString(p.substring(0, i)); } Engine.logCertificateManager.debug("(MySSLSocketFactory) PIN code: " + pinCode); ks = KeyStore.getInstance("pkcs11", providerName); ks.load((InputStream) null, pinCode.toCharArray()); kmf.init(ks, null); } else { ks = KeyStore.getInstance(keyStoreType); passPhrase = keyStorePassword.toCharArray(); ks.load(new FileInputStream(keyStore), passPhrase); kmf.init(ks, passPhrase); } } Engine.logCertificateManager.debug("(MySSLSocketFactory) Client alias: " + (alias == null ? "<to be chosen by the security implementor>" : alias)); ts = KeyStore.getInstance("jks"); passPhrase = trustStorePassword.toCharArray(); if (trustStore.equals("")) ts.load(null, passPhrase); else ts.load(new FileInputStream(trustStore), passPhrase); algorithm = TrustManagerFactory.getDefaultAlgorithm(); Engine.logCertificateManager.debug("(MySSLSocketFactory) Using TrustManager algorithm " + algorithm); TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm); tmf.init(ts); TrustManager[] tm = { TRUST_MANAGER }; MyX509KeyManager xkm = new MyX509KeyManager((X509KeyManager) kmf.getKeyManagers()[0], ks, ts, alias); Engine.logCertificateManager .debug("(MySSLSocketFactory) trusting all certificates : " + trustAllServerCertificates); //SSLContext context = SSLContext.getInstance("SSLv3"); SSLContext context = SSLContext.getInstance("TLS"); if (trustAllServerCertificates) context.init(new KeyManager[] { xkm }, tm, null); else context.init(new KeyManager[] { xkm }, tmf.getTrustManagers(), null); Engine.logCertificateManager.debug("(MySSLSocketFactory) SSL context created: " + context.getProtocol()); return context; }
From source file:com.elkriefy.android.apps.authenticationexample.credentialsgrace.CredGraceActivity.java
/** * Creates a symmetric key in the Android Key Store which can only be used after the user has * authenticated with device credentials within the last X seconds. */// w w w. java2 s . co m private void createKey() { // Generate a key to decrypt payment credentials, tokens, etc. // This will most likely be a registration step for the user when they are setting up your app. try { KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); keyStore.load(null); KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); // Set the alias of the entry in Android KeyStore where the key will appear // and the constrains (purposes) in the constructor of the Builder keyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_CBC).setUserAuthenticationRequired(true) // Require that the user has unlocked in the last 30 seconds .setUserAuthenticationValidityDurationSeconds(AUTHENTICATION_DURATION_SECONDS) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7).build()); keyGenerator.generateKey(); } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException | KeyStoreException | CertificateException | IOException e) { throw new RuntimeException("Failed to create a symmetric key", e); } }
From source file:com.amazon.alexa.avs.companion.ProvisioningClient.java
private SSLSocketFactory getPinnedSSLSocketFactory(Context context) throws Exception { InputStream caCertInputStream = null; try {//from w ww . ja v a 2 s.c o m caCertInputStream = context.getResources().openRawResource(R.raw.ca); CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate caCert = cf.generateCertificate(caCertInputStream); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); trustStore.setCertificateEntry("myca", caCert); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustManagerFactory.getTrustManagers(), null); return sslContext.getSocketFactory(); } finally { IOUtils.closeQuietly(caCertInputStream); } }