List of usage examples for java.security KeyStore load
public final void load(InputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException
From source file:com.microsoft.aad.adal4j.AsymmetricKeyCredential.java
/** * Static method to create KeyCredential instance. * /*from w w w.j a v a2s . c o m*/ * @param clientId * Identifier of the client requesting the token. * @param pkcs12Certificate * PKCS12 certificate stream containing public and private key. * Caller is responsible for handling the input stream. * @param password * certificate password * @return KeyCredential instance * @throws KeyStoreException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws CertificateException * @throws FileNotFoundException * @throws IOException * @throws UnrecoverableKeyException */ public static AsymmetricKeyCredential create(final String clientId, final InputStream pkcs12Certificate, final String password) throws KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, UnrecoverableKeyException { final KeyStore keystore = KeyStore.getInstance("PKCS12", "SunJSSE"); keystore.load(pkcs12Certificate, password.toCharArray()); final Enumeration<String> aliases = keystore.aliases(); final String alias = aliases.nextElement(); final PrivateKey key = (PrivateKey) keystore.getKey(alias, password.toCharArray()); final X509Certificate publicCertificate = (X509Certificate) keystore.getCertificate(alias); return create(clientId, key, publicCertificate); }
From source file:ee.sk.hwcrypto.demo.signature.TestSigningData.java
private static X509Certificate getSigningCert(String pkiContainer, String pkiContainerPassword) { try {//from ww w . j a v a2 s. c om KeyStore keyStore = KeyStore.getInstance("PKCS12"); try (FileInputStream stream = new FileInputStream(pkiContainer)) { keyStore.load(stream, pkiContainerPassword.toCharArray()); } return (X509Certificate) keyStore.getCertificate("1"); } catch (Exception e) { throw new RuntimeException("Loading signer cert failed"); } }
From source file:io.specto.hoverfly.junit.HoverflyRuleUtils.java
static void setHoverflyTrustStore() throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, KeyManagementException, URISyntaxException { // load your key store as a stream and initialize a KeyStore InputStream trustStream = findResourceOnClasspath("hoverfly.jks").toURL().openStream(); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); // load the stream to your store trustStore.load(trustStream, "hoverfly".toCharArray()); // initialize a trust manager factory with the trusted store TrustManagerFactory trustFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustFactory.init(trustStore);// ww w .jav a 2 s. co m // get the trust managers from the factory TrustManager[] trustManagers = trustFactory.getTrustManagers(); // initialize an ssl context to use these managers and set as default SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustManagers, null); SSLContext.setDefault(sslContext); }
From source file:org.gvnix.service.roo.addon.addon.security.GvNix509TrustManager.java
/** * Loads keystore in the given file using passphrase as keystore password. * //from w w w . j a va 2 s .c o m * @param keystore * @param pass * @return * @throws Exception will be a IOExecption if the given password is a wrong * one */ public static KeyStore loadKeyStore(File keystore, char[] pass) throws Exception { Validate.notNull(keystore, "keystore must be a vaild keystore file"); InputStream in = new FileInputStream(keystore); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(in, pass); in.close(); return ks; }
From source file:mitm.common.tools.OpenSSLWrapperTest.java
private static KeyStore loadKeyStore(File file, String password) throws KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException { KeyStore keyStore = securityFactory.createKeyStore("PKCS12"); // initialize key store keyStore.load(new FileInputStream(file), password.toCharArray()); return keyStore; }
From source file:com.apporiented.hermesftp.utils.SecurityUtil.java
/** * Create the security context required for SSL communication. * //from w w w . j av a 2s .c om * @param keyStoreFile The name of the keystore file. * @param keyStorePassword The password for the keystore. * @return The context. * @throws FtpConfigException Thrown on error in configuration. */ public static SSLContext createSslContext(String keyStoreFile, char[] keyStorePassword) throws FtpConfigException { SSLContext sslContext; try { /* Get keystore file and password */ InputStream ksInputStream = getKeyStoreInputStream(keyStoreFile); /* * Get the java keystore object an key manager. A keystore is where keys and * certificates are kept. */ KeyStore keystore = KeyStore.getInstance("JKS"); keystore.load(ksInputStream, keyStorePassword); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(keystore, keyStorePassword); /* * An SSLContext is an environment for implementing JSSE. It is used to create a * ServerSocketFactory */ sslContext = SSLContext.getInstance("SSL"); sslContext.init(kmf.getKeyManagers(), null, null); } catch (KeyManagementException e) { throw new SecurityException("A key management authorization problem occurred."); } catch (FileNotFoundException e) { throw new SecurityException("The key store file could not be found."); } catch (KeyStoreException e) { throw new SecurityException("A key store problem occurred."); } catch (NoSuchAlgorithmException e) { throw new SecurityException("The hash algorithm is not supported."); } catch (CertificateException e) { throw new SecurityException("Certificate could not be loaded."); } catch (UnrecoverableKeyException e) { throw new SecurityException("Key store cannot be recovered."); } catch (IOException e) { throw new SecurityException("Reading the key store failed."); } return sslContext; }
From source file:org.jwebsocket.sso.HTTPSupport.java
/** * * @param aURL/*from ww w.ja v a2 s.c o m*/ * @param aMethod * @param aHeaders * @param aPostBody * @param aTimeout * @return */ public static String request(String aURL, String aMethod, Map<String, String> aHeaders, String aPostBody, long aTimeout) { if (mLog.isDebugEnabled()) { mLog.debug("Requesting (" + aMethod + ") '" + aURL + "', timeout: " + aTimeout + "ms, Headers: " + aHeaders + ", Body: " + (null != aPostBody ? "'" + aPostBody.replace("\n", "\\n").replace("\r", "\\r") + "'" : "[null]")); } String lResponse = "{\"code\": -1, \"msg\": \"undefined\""; try { KeyStore lTrustStore = KeyStore.getInstance(KeyStore.getDefaultType()); lTrustStore.load(null, null); // Trust own CA and all self-signed certs SSLContext lSSLContext = SSLContexts.custom() .loadTrustMaterial(lTrustStore, new TrustSelfSignedStrategy()).build(); // Allow TLSv1 protocol only SSLConnectionSocketFactory lSSLFactory = new SSLConnectionSocketFactory(lSSLContext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); CloseableHttpClient lHTTPClient = HttpClients.custom().setSSLSocketFactory(lSSLFactory).build(); HttpUriRequest lRequest; if ("POST".equals(aMethod)) { lRequest = new HttpPost(aURL); ((HttpPost) lRequest).setEntity(new ByteArrayEntity(aPostBody.getBytes("UTF-8"))); } else { lRequest = new HttpGet(aURL); } for (Map.Entry<String, String> lEntry : aHeaders.entrySet()) { lRequest.setHeader(lEntry.getKey(), lEntry.getValue()); } // System.out.println("Executing request " + lRequest.getRequestLine()); // Create a custom response handler ResponseHandler<String> lResponseHandler = new ResponseHandler<String>() { @Override public String handleResponse(final HttpResponse lResponse) throws ClientProtocolException, IOException { int lStatus = lResponse.getStatusLine().getStatusCode(); HttpEntity lEntity = lResponse.getEntity(); return lEntity != null ? EntityUtils.toString(lEntity) : null; // if (lStatus >= 200 && lStatus < 300) { // HttpEntity entity = lResponse.getEntity(); // return entity != null ? EntityUtils.toString(entity) : null; // } else { // throw new ClientProtocolException("Unexpected response status: " + lStatus); // } } }; long lStartedAt = System.currentTimeMillis(); lResponse = lHTTPClient.execute(lRequest, lResponseHandler); if (mLog.isDebugEnabled()) { mLog.debug("Response (" + (System.currentTimeMillis() - lStartedAt) + "ms): '" + lResponse.replace("\n", "\\n").replace("\r", "\\r") + "'"); } return lResponse; } catch (Exception lEx) { String lMsg = "{\"code\": -1, \"msg\": \"" + lEx.getClass().getSimpleName() + " at http request: " + lEx.getMessage() + "\"}"; mLog.error(lEx.getClass().getSimpleName() + ": " + lEx.getMessage() + ", returning: " + lMsg); lResponse = lMsg; return lResponse; } }
From source file:ee.sk.hwcrypto.demo.signature.TestSigningData.java
private static byte[] sign(byte[] dataToSign, DigestAlgorithm digestAlgorithm) { try {//from ww w. j ava 2s .com KeyStore keyStore = KeyStore.getInstance("PKCS12"); try (FileInputStream stream = new FileInputStream(TEST_PKI_CONTAINER)) { keyStore.load(stream, TEST_PKI_CONTAINER_PASSWORD.toCharArray()); } PrivateKey privateKey = (PrivateKey) keyStore.getKey("1", TEST_PKI_CONTAINER_PASSWORD.toCharArray()); final String javaSignatureAlgorithm = "NONEwith" + privateKey.getAlgorithm(); return encrypt(javaSignatureAlgorithm, privateKey, addPadding(dataToSign, digestAlgorithm)); } catch (Exception e) { throw new DigiDoc4JException("Loading private key failed"); } }
From source file:com.openmeap.util.SSLUtils.java
static public HttpClient getRelaxedSSLVerificationHttpClient() { try {/*from ww w. java 2 s . c o m*/ KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new MySSLSocketFactory(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, FormConstants.CHAR_ENC_DEFAULT); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); return new DefaultHttpClient(ccm, params); } catch (Exception e) { return new DefaultHttpClient(); } }
From source file:org.openo.nfvo.vnfmadapter.service.csm.connect.AbstractSslContext.java
protected static KeyManager[] createKeyManager(JSONObject sslConf) { KeyManager[] kms = null;/*from w w w . ja v a2 s . co m*/ try { String CERT_STORE = "etc/conf/server.p12"; String CERT_STORE_PASSWORD = "Changeme_123"; String KEY_STORE_TYPE = "PKCS12"; if (sslConf != null) { CERT_STORE = sslConf.getString("keyStore"); CERT_STORE_PASSWORD = sslConf.getString("keyStorePass"); KEY_STORE_TYPE = sslConf.getString("keyStoreType"); } // load jks file FileInputStream f_certStore = new FileInputStream(CERT_STORE); KeyStore ks = KeyStore.getInstance(KEY_STORE_TYPE); ks.load(f_certStore, CERT_STORE_PASSWORD.toCharArray()); f_certStore.close(); // init and create String alg = KeyManagerFactory.getDefaultAlgorithm(); KeyManagerFactory kmFact = KeyManagerFactory.getInstance(alg); kmFact.init(ks, CERT_STORE_PASSWORD.toCharArray()); kms = kmFact.getKeyManagers(); } catch (Exception e) { LOG.error("create KeyManager fail!", e); } return kms; }