List of usage examples for java.security KeyStore getInstance
public static KeyStore getInstance(String type) throws KeyStoreException
From source file:org.ulyssis.ipp.publisher.HttpServerPublisher.java
private SSLContext sslContext() { try {/*www. jav a 2 s. c om*/ KeyStore cks = KeyStore.getInstance(KeyStore.getDefaultType()); cks.load(new FileInputStream(options.getKeystore().get().toFile()), options.getKeystorePass().toCharArray()); SSLContextBuilder builder = SSLContexts.custom(); if (options.getTruststore().isPresent()) { KeyStore tks = KeyStore.getInstance(KeyStore.getDefaultType()); tks.load(new FileInputStream(options.getTruststore().get().toFile()), options.getTruststorePass().toCharArray()); builder.loadTrustMaterial(tks, new TrustSelfSignedStrategy()); } return builder.loadKeyMaterial(cks, options.getKeystorePass().toCharArray()).build(); } catch (Exception e) { // TODO: DO SOMETHING WITH THE EXCEPTION! LOG.error("Exception", e); } return null; }
From source file:com.netflix.spinnaker.orca.webhook.config.WebhookConfiguration.java
private Optional<KeyStore> getCustomKeyStore() { WebhookProperties.TrustSettings trustSettings = webhookProperties.getTrust(); if (trustSettings == null || !trustSettings.isEnabled() || StringUtils.isEmpty(trustSettings.getTrustStore())) { return Optional.empty(); }/*from ww w.j a v a 2s . com*/ KeyStore keyStore; try { keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); } catch (KeyStoreException e) { throw new RuntimeException(e); } try (FileInputStream file = new FileInputStream(trustSettings.getTrustStore())) { keyStore.load(file, trustSettings.getTrustStorePassword().toCharArray()); } catch (CertificateException | IOException | NoSuchAlgorithmException e) { throw new RuntimeException(e); } return Optional.of(keyStore); }
From source file:cvut.fel.mobilevoting.murinrad.communications.Connection.java
/** * Initializes the HTTPs connection/* ww w .java 2 s .c om*/ * * @param sslPort * the number of the port the server should be listening for * SSL/TLS connections */ public void InitializeSecure(int sslPort) { if (sslPort != -1) { SSLSocketFactory sslf = null; SSLSocket s = null; port = sslPort; try { // notifyOfProggress(false); KeyStore trusted = KeyStore.getInstance(KeyStore.getDefaultType()); trusted.load(null, null); sslf = new MySSLSocketFactory(trusted); Log.w("Android mobile voting", "1"); sslf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Log.w("Android mobile voting", "2"); BasicHttpParams params = new BasicHttpParams(); Log.w("Android mobile voting", "3"); HttpConnectionParams.setConnectionTimeout(params, 500); Log.w("Android mobile voting", "4"); s = (SSLSocket) sslf.connectSocket(sslf.createSocket(), server.getAddress(), sslPort, null, 0, params); if (exc) { SSLSession ssls = null; ssls = s.getSession(); final javax.security.cert.X509Certificate[] x = ssls.getPeerCertificateChain(); for (int i = 0; i < x.length; i++) { parent.mHandler.post(new Runnable() { @Override public void run() { try { parent.askForTrust(getThumbPrint(x[0]), instance); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CertificateEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (final Exception ex) { parent.mHandler.post(new Runnable() { @Override public void run() { parent.showToast(ex.toString()); } }); Log.w("Android Mobile Voting", "400 Error"); parent.finish(); } } }); } } s.startHandshake(); Scheme https = new Scheme("https", sslf, sslPort); schemeRegistry.register(https); usingScheme = "https"; port = sslPort; if (!exc) retrieveQuestions(); } catch (final Exception ex) { parent.mHandler.post(new Runnable() { @Override public void run() { parent.showToast(ex.toString()); } }); // Log.w("Android Mobile Voting", "400 Error"); parent.finish(); } } else { parent.mHandler.post(new Runnable() { @Override public void run() { parent.showNoSSLDialog(instance); } }); } }
From source file:edu.washington.iam.tools.IamConnectionManager.java
protected void initManagers() { // trust managers /**/*from ww w.j a v a 2 s . c om*/ try { TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); X509Certificate cert = null; if (caFilename!=null) cert = readCertificate(caFilename); log.debug("init trust mgr " + cert); trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); trustStore.setCertificateEntry("CACERT", cert); tmf.init(trustStore); trustManagers = tmf.getTrustManagers(); } catch (Exception e) { log.error("cacert error: " + e); } **/ trustManagers = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { return; } public void checkServerTrusted(X509Certificate[] certs, String authType) { return; } } }; // key managers if (certFilename != null && keyFilename != null) { try { KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); X509Certificate cert = readCertificate(certFilename); PKCS1 pkcs = new PKCS1(); PrivateKey key = pkcs.readKey(keyFilename); X509Certificate[] chain = new X509Certificate[1]; chain[0] = cert; keyStore.setKeyEntry("CERT", (Key) key, "pw".toCharArray(), chain); kmf.init(keyStore, "pw".toCharArray()); keyManagers = kmf.getKeyManagers(); } catch (Exception e) { log.error("cert/key error: " + e); } } }
From source file:ucar.httpservices.CustomSSLProtocolSocketFactory.java
static KeyStore buildstore(String path, String password, String prefix) throws HTTPException { KeyStore store = null;/* w ww . ja v a 2 s.c om*/ try { if (path != null && password != null) { File storefile = new File(path); if (!storefile.canRead()) throw new HTTPException( "Cannot read specified " + prefix + "store:" + storefile.getAbsolutePath()); store = KeyStore.getInstance("JKS"); InputStream is = null; try { is = new FileInputStream(storefile); store.load(is, password.toCharArray()); } finally { if (is != null) is.close(); } } } catch (Exception e) { throw new HTTPException(e); } return store; }
From source file:org.elasticsearch.xpack.ssl.SSLClientAuthTests.java
private SSLContext getSSLContext() { try (InputStream in = Files.newInputStream( getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testclient.jks"))) { KeyStore keyStore = KeyStore.getInstance("jks"); keyStore.load(in, "testclient".toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(keyStore);/*from www . j av a 2s .co m*/ KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keyStore, "testclient".toCharArray()); SSLContext context = SSLContext.getInstance("TLSv1.2"); context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom()); return context; } catch (Exception e) { throw new ElasticsearchException("failed to initialize a TrustManagerFactory", e); } }
From source file:it.cnr.icar.eric.server.security.authentication.CertificateAuthority.java
/** Extension request to sign specified cert and return the signed cert. */ @SuppressWarnings("static-access") public RegistryResponseHolder signCertificateRequest(UserType user, RegistryRequestType req, Map<?, ?> idToRepositoryItemMap) throws RegistryException { RegistryResponseHolder respHolder = null; RegistryResponseType ebRegistryResponseType = null; ServerRequestContext context = null; try {// w w w . ja va 2s. co m context = new ServerRequestContext("CertificateAUthority.signCertificateRequest", req); context.setUser(user); if (idToRepositoryItemMap.keySet().size() == 0) { throw new MissingRepositoryItemException( ServerResourceBundle.getInstance().getString("message.KSRepItemNotFound")); } String id = (String) idToRepositoryItemMap.keySet().iterator().next(); Object obj = idToRepositoryItemMap.get(id); if (!(obj instanceof RepositoryItem)) { throw new InvalidContentException(); } RepositoryItem ri = (RepositoryItem) obj; //This is the JKS keystore containing cert to be signed //Read original cert from keystore InputStream is = ri.getDataHandler().getInputStream(); KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(is, bu.FREEBXML_REGISTRY_KS_PASS_REQ.toCharArray()); is.close(); X509Certificate cert = (X509Certificate) keyStore .getCertificate(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_REQ); //Sign the cert cert = signCertificate(cert); //Replace cert with signed cert in keystore keyStore.deleteEntry(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_REQ); keyStore.setCertificateEntry(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_RESP, cert); //Add CA root cert (RegistryOPerator's cert) to keystore. keyStore.setCertificateEntry(bu.FREEBXML_REGISTRY_CACERT_ALIAS, getCACertificate()); Certificate[] certChain = new Certificate[2]; certChain[0] = cert; certChain[1] = getCACertificate(); validateChain(certChain); File repositoryItemFile = File.createTempFile(".eric-ca-resp", ".jks"); repositoryItemFile.deleteOnExit(); FileOutputStream fos = new java.io.FileOutputStream(repositoryItemFile); keyStore.store(fos, bu.FREEBXML_REGISTRY_KS_PASS_RESP.toCharArray()); fos.flush(); fos.close(); DataHandler dh = new DataHandler(new FileDataSource(repositoryItemFile)); RepositoryItemImpl riNew = new RepositoryItemImpl(id, dh); ebRegistryResponseType = bu.rsFac.createRegistryResponseType(); ebRegistryResponseType.setStatus(BindingUtility.CANONICAL_RESPONSE_STATUS_TYPE_ID_Success); HashMap<String, Object> respIdToRepositoryItemMap = new HashMap<String, Object>(); respIdToRepositoryItemMap.put(id, riNew); respHolder = new RegistryResponseHolder(ebRegistryResponseType, respIdToRepositoryItemMap); } catch (RegistryException e) { context.rollback(); throw e; } catch (Exception e) { context.rollback(); throw new RegistryException(e); } context.commit(); return respHolder; }
From source file:$.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 w ww . ja va2 s . co m*/ * @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:cybervillains.ca.KeyStoreManager.java
@SuppressWarnings("unchecked") public KeyStoreManager(File root) { this.root = root; Security.insertProviderAt(new BouncyCastleProvider(), 2); _sr = new SecureRandom(); try {/*from ww w. jav a 2s .com*/ _rsaKpg = KeyPairGenerator.getInstance(RSA_KEYGEN_ALGO); _dsaKpg = KeyPairGenerator.getInstance(DSA_KEYGEN_ALGO); } catch (Throwable t) { throw new Error(t); } try { File privKeys = new File(root, KEYMAP_SER_FILE); if (!privKeys.exists()) { _rememberedPrivateKeys = new HashMap<PublicKey, PrivateKey>(); } else { ObjectInputStream in = new ObjectInputStream(new FileInputStream(privKeys)); // Deserialize the object _rememberedPrivateKeys = (HashMap<PublicKey, PrivateKey>) in.readObject(); in.close(); } File pubKeys = new File(root, PUB_KEYMAP_SER_FILE); if (!pubKeys.exists()) { _mappedPublicKeys = new HashMap<PublicKey, PublicKey>(); } else { ObjectInputStream in = new ObjectInputStream(new FileInputStream(pubKeys)); // Deserialize the object _mappedPublicKeys = (HashMap<PublicKey, PublicKey>) in.readObject(); in.close(); } } catch (FileNotFoundException e) { // check for file exists, won't happen. e.printStackTrace(); } catch (IOException e) { // we could correct, but this probably indicates a corruption // of the serialized file that we want to know about; likely // synchronization problems during serialization. e.printStackTrace(); throw new Error(e); } catch (ClassNotFoundException e) { // serious problem. e.printStackTrace(); throw new Error(e); } _rsaKpg.initialize(1024, _sr); _dsaKpg.initialize(1024, _sr); try { _ks = KeyStore.getInstance("JKS"); reloadKeystore(); } catch (FileNotFoundException fnfe) { try { createKeystore(); } catch (Exception e) { throw new Error(e); } } catch (Exception e) { throw new Error(e); } try { File file = new File(root, CERTMAP_SER_FILE); if (!file.exists()) { _certMap = new HashMap<String, String>(); } else { ObjectInputStream in = new ObjectInputStream(new FileInputStream(file)); // Deserialize the object _certMap = (HashMap<String, String>) in.readObject(); in.close(); } } catch (FileNotFoundException e) { // won't happen, check file.exists() e.printStackTrace(); } catch (IOException e) { // corrupted file, we want to know. e.printStackTrace(); throw new Error(e); } catch (ClassNotFoundException e) { // something very wrong, exit e.printStackTrace(); throw new Error(e); } try { File file = new File(root, SUBJMAP_SER_FILE); if (!file.exists()) { _subjectMap = new HashMap<String, String>(); } else { ObjectInputStream in = new ObjectInputStream(new FileInputStream(file)); // Deserialize the object _subjectMap = (HashMap<String, String>) in.readObject(); in.close(); } } catch (FileNotFoundException e) { // won't happen, check file.exists() e.printStackTrace(); } catch (IOException e) { // corrupted file, we want to know. e.printStackTrace(); throw new Error(e); } catch (ClassNotFoundException e) { // something very wrong, exit e.printStackTrace(); throw new Error(e); } }
From source file:com.hybris.datahub.outbound.utils.RestTemplateUtil.java
private LayeredConnectionSocketFactory setUpSSL() { LayeredConnectionSocketFactory sslSF = null; try {/*from w w w .ja v a 2s . c o m*/ final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); final SSLContext sslContext = SSLContexts.custom().useTLS() .loadTrustMaterial(trustStore, new AnyTrustStrategy()).build(); sslSF = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } catch (final Exception e) { LOGGER.error(e.getMessage()); } return sslSF; }