List of usage examples for java.security KeyStore load
public final void load(InputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException
From source file:ddf.security.sts.claimsHandler.ClaimsHandlerManager.java
public static TrustManagerFactory createTrustManagerFactory(String trustStoreLoc, String trustStorePass) throws IOException { TrustManagerFactory tmf;/*from www . j av a2 s. co m*/ try { // truststore stuff KeyStore trustStore = KeyStore.getInstance(System.getProperty("javax.net.ssl.keyStoreType")); LOGGER.debug("trustStoreLoc = {}", trustStoreLoc); FileInputStream trustFIS = new FileInputStream(trustStoreLoc); try { LOGGER.debug("Loading trustStore"); trustStore.load(trustFIS, trustStorePass.toCharArray()); } catch (CertificateException e) { throw new IOException("Unable to load certificates from truststore. " + trustStoreLoc, e); } finally { IOUtils.closeQuietly(trustFIS); } tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(trustStore); LOGGER.debug("trust manager factory initialized"); } catch (NoSuchAlgorithmException e) { throw new IOException( "Problems creating SSL socket. Usually this is " + "referring to the certificate sent by the server not being trusted by the client.", e); } catch (KeyStoreException e) { throw new IOException("Unable to read keystore. " + trustStoreLoc, e); } return tmf; }
From source file:net.sf.jsignpdf.utils.KeyStoreUtils.java
/** * Loads the default root certificates at * <java.home>/lib/security/cacerts. * /*from ww w . ja v a 2s .c o m*/ * @param provider * the provider or <code>null</code> for the default provider * @return a <CODE>KeyStore</CODE> */ public static KeyStore loadCacertsKeyStore(String provider) { File file = new File(System.getProperty("java.home"), "lib"); file = new File(file, "security"); file = new File(file, "cacerts"); FileInputStream fin = null; try { fin = new FileInputStream(file); KeyStore k; if (provider == null) k = KeyStore.getInstance("JKS"); else k = KeyStore.getInstance("JKS", provider); k.load(fin, null); return k; } catch (Exception e) { e.printStackTrace(); return null; } finally { try { if (fin != null) { fin.close(); } } catch (Exception ex) { } } }
From source file:ucar.httpservices.CustomSSLProtocolSocketFactory.java
static KeyStore buildstore(String path, String password, String prefix) throws HTTPException { KeyStore store = null; try {/*from ww w . j a va 2s .c o m*/ 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:com.sonatype.nexus.ssl.plugin.internal.TrustStoreImpl.java
private static KeyManager[] getSystemKeyManagers() throws Exception { KeyManagerFactory keyManagerFactory; String keyAlgorithm = System.getProperty("ssl.KeyManagerFactory.algorithm"); if (keyAlgorithm == null) { keyAlgorithm = KeyManagerFactory.getDefaultAlgorithm(); }/*from w w w . j ava 2 s . c o m*/ String keyStoreType = System.getProperty("javax.net.ssl.keyStoreType"); if (keyStoreType == null) { keyStoreType = KeyStore.getDefaultType(); } if ("none".equalsIgnoreCase(keyStoreType)) { keyManagerFactory = KeyManagerFactory.getInstance(keyAlgorithm); } else { final String keyStoreFileName = System.getProperty("javax.net.ssl.keyStore"); if (keyStoreFileName != null) { File keyStoreFile = new File(keyStoreFileName); keyManagerFactory = KeyManagerFactory.getInstance(keyAlgorithm); String keyStoreProvider = System.getProperty("javax.net.ssl.keyStoreProvider"); KeyStore keyStore; if (keyStoreProvider != null) { keyStore = KeyStore.getInstance(keyStoreType, keyStoreProvider); } else { keyStore = KeyStore.getInstance(keyStoreType); } String password = System.getProperty("javax.net.ssl.keyStorePassword"); try (FileInputStream in = new FileInputStream(keyStoreFile)) { keyStore.load(in, password != null ? password.toCharArray() : null); } keyManagerFactory.init(keyStore, password != null ? password.toCharArray() : null); } else { return null; } } return keyManagerFactory.getKeyManagers(); }
From source file:com.indivica.olis.Driver.java
public static String signData(String data) { X509Certificate cert = null;/*ww w .ja v a 2 s .com*/ PrivateKey priv = null; KeyStore keystore = null; String pwd = "Olis2011"; String result = null; try { Security.addProvider(new BouncyCastleProvider()); keystore = KeyStore.getInstance("PKCS12", "SunJSSE"); // Load the keystore keystore.load(new FileInputStream(OscarProperties.getInstance().getProperty("olis_keystore")), pwd.toCharArray()); Enumeration e = keystore.aliases(); String name = ""; if (e != null) { while (e.hasMoreElements()) { String n = (String) e.nextElement(); if (keystore.isKeyEntry(n)) { name = n; } } } // Get the private key and the certificate priv = (PrivateKey) keystore.getKey(name, pwd.toCharArray()); cert = (X509Certificate) keystore.getCertificate(name); // I'm not sure if this is necessary ArrayList<Certificate> certList = new ArrayList<Certificate>(); certList.add(cert); Store certs = new JcaCertStore(certList); // Encrypt data CMSSignedDataGenerator sgen = new CMSSignedDataGenerator(); // What digest algorithm i must use? SHA1? MD5? RSA?... ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(priv); sgen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(sha1Signer, cert)); // I'm not sure this is necessary sgen.addCertificates(certs); // I think that the 2nd parameter need to be false (detached form) CMSSignedData csd = sgen.generate(new CMSProcessableByteArray(data.getBytes()), true); byte[] signedData = csd.getEncoded(); byte[] signedDataB64 = Base64.encode(signedData); result = new String(signedDataB64); } catch (Exception e) { MiscUtils.getLogger().error("Can't sign HL7 message for OLIS", e); } return result; }
From source file:cn.digirun.frame.payment.wxpay.util.ClientCustomSSL.java
public static String doRefund(String url, String data) throws Exception { /**/* w w w. j a va2 s . c o m*/ * ?PKCS12? ?-- API */ KeyStore keyStore = KeyStore.getInstance("PKCS12"); /** * ? */ //ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX+ ""); // FileInputStream instream = new FileInputStream(new File("D:/Program Files/MyEclipse 6.5/workspace/weidian/WebRoot/cer/apiclient_cert.p12"));//P12 FileInputStream instream = new FileInputStream( ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + WxpayConfig.cert_path)); try { /** * ? * MCHID * */ keyStore.load(instream, WxpayConfig.mch_id.toCharArray()); } finally { instream.close(); } SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, WxpayConfig.mch_id.toCharArray())//? .build(); // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); try { HttpPost httpost = new HttpPost(url); // ?? httpost.addHeader("Connection", "keep-alive"); httpost.addHeader("Accept", "*/*"); httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); httpost.addHeader("Host", "api.mch.weixin.qq.com"); httpost.addHeader("X-Requested-With", "XMLHttpRequest"); httpost.addHeader("Cache-Control", "max-age=0"); httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) "); httpost.setEntity(new StringEntity(data, "UTF-8")); CloseableHttpResponse response = httpclient.execute(httpost); try { HttpEntity entity = response.getEntity(); String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8"); EntityUtils.consume(entity); return jsonStr; } finally { response.close(); } } finally { httpclient.close(); } }
From source file:com.eastedge.readnovel.weibo.net.Utility.java
public static HttpClient getNewHttpClient(Context context) { try {/*from w ww . 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(); HttpConnectionParams.setConnectionTimeout(params, 10000); HttpConnectionParams.setSoTimeout(params, 10000); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); 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); // Set the default socket timeout (SO_TIMEOUT) // in // milliseconds which is the timeout for waiting for data. HttpConnectionParams.setConnectionTimeout(params, Utility.SET_CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(params, Utility.SET_SOCKET_TIMEOUT); HttpClient client = new DefaultHttpClient(ccm, params); WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (!wifiManager.isWifiEnabled()) { Uri uri = Uri.parse("content://telephony/carriers/preferapn"); Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null); if (mCursor != null && mCursor.moveToFirst()) { String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy")); if (proxyStr != null && proxyStr.trim().length() > 0) { HttpHost proxy = new HttpHost(proxyStr, 80); client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy); } mCursor.close(); } } return client; } catch (Exception e) { return new DefaultHttpClient(); } }
From source file:com.fada.sellsteward.myweibo.sina.net.Utility.java
public static HttpClient getNewHttpClient(Context context) { try {/*from www . ja va2 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(); HttpConnectionParams.setConnectionTimeout(params, 10000); HttpConnectionParams.setSoTimeout(params, 10000); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); 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); // Set the default socket timeout (SO_TIMEOUT) // in // milliseconds which is the timeout for waiting for data. HttpConnectionParams.setConnectionTimeout(params, Utility.SET_CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(params, Utility.SET_SOCKET_TIMEOUT); HttpClient client = new DefaultHttpClient(ccm, params); WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (!wifiManager.isWifiEnabled()) { // ??APN Uri uri = Uri.parse("content://telephony/carriers/preferapn"); Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null); if (mCursor != null && mCursor.moveToFirst()) { // ??? String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy")); if (proxyStr != null && proxyStr.trim().length() > 0) { HttpHost proxy = new HttpHost(proxyStr, 80); client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy); } mCursor.close(); } } return client; } catch (Exception e) { return new DefaultHttpClient(); } }
From source file:com.indivica.olis.Driver.java
public static String signData2(String data) { X509Certificate cert = null;//w w w .j a v a 2s . c om PrivateKey priv = null; KeyStore keystore = null; String pwd = OscarProperties.getInstance().getProperty("olis_ssl_keystore_password", "changeit"); String result = null; try { Security.addProvider(new BouncyCastleProvider()); keystore = KeyStore.getInstance("JKS"); // Load the keystore keystore.load(new FileInputStream(OscarProperties.getInstance().getProperty("olis_keystore")), pwd.toCharArray()); //Enumeration e = keystore.aliases(); String name = "olis"; // Get the private key and the certificate priv = (PrivateKey) keystore.getKey(name, pwd.toCharArray()); FileInputStream is = new FileInputStream( OscarProperties.getInstance().getProperty("olis_returned_cert")); CertificateFactory cf = CertificateFactory.getInstance("X.509"); cert = (X509Certificate) cf.generateCertificate(is); // I'm not sure if this is necessary ArrayList<Certificate> certList = new ArrayList<Certificate>(); certList.add(cert); Store certs = new JcaCertStore(certList); // Encrypt data CMSSignedDataGenerator sgen = new CMSSignedDataGenerator(); // What digest algorithm i must use? SHA1? MD5? RSA?... ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(priv); sgen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(sha1Signer, cert)); // I'm not sure this is necessary sgen.addCertificates(certs); // I think that the 2nd parameter need to be false (detached form) CMSSignedData csd = sgen.generate(new CMSProcessableByteArray(data.getBytes()), true); byte[] signedData = csd.getEncoded(); byte[] signedDataB64 = Base64.encode(signedData); result = new String(signedDataB64); } catch (Exception e) { MiscUtils.getLogger().error("Can't sign HL7 message for OLIS", e); } return result; }
From source file:net.sf.jsignpdf.utils.KeyStoreUtils.java
/** * Opens given keystore./*from w ww . j a v a2s .c o m*/ * * @param aKsType * @param aKsFile * @param aKsPasswd * @return */ public static KeyStore loadKeyStore(String aKsType, final String aKsFile, final char[] aKsPasswd) { if (StringUtils.isEmpty(aKsType) && StringUtils.isEmpty(aKsFile)) { return loadCacertsKeyStore(null); } if (StringUtils.isEmpty(aKsType)) { aKsType = KeyStore.getDefaultType(); } KeyStore tmpKs = null; InputStream tmpIS = null; try { tmpKs = KeyStore.getInstance(aKsType); if (StringUtils.isNotEmpty(aKsFile)) { tmpIS = new FileInputStream(aKsFile); } tmpKs.load(tmpIS, aKsPasswd); fixAliases(tmpKs); } catch (Exception e) { e.printStackTrace(); return null; } finally { if (tmpIS != null) try { tmpIS.close(); } catch (Exception e) { } } return tmpKs; }