List of usage examples for java.security KeyStore getInstance
public static KeyStore getInstance(String type) throws KeyStoreException
From source file:org.gzk.image.junit.ClientCustomSSL.java
public final static void main(String[] args) throws Exception { KeyStore keyStore = KeyStore.getInstance("PKCS12"); FileInputStream instream = new FileInputStream(new File("D:/apiclient_cert.p12")); try {/* w w w. j ava 2 s .c o m*/ keyStore.load(instream, "1374938902".toCharArray()); } finally { instream.close(); } // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "1374938902".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 { HttpGet httpget = new HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund"); System.out.println("executing request" + httpget.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpget); try { HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent())); String text; while ((text = bufferedReader.readLine()) != null) { System.out.println(text); } } EntityUtils.consume(entity); } finally { response.close(); } } finally { httpclient.close(); } }
From source file:com.magicbeans.banjiuwan.util.ClientCustomSSL.java
public final static void main(String[] args) throws Exception { KeyStore keyStore = KeyStore.getInstance("PKCS12"); FileInputStream instream = new FileInputStream(new File("D:/10016225.p12")); try {//from w w w .j a va 2 s . c o m keyStore.load(instream, "10016225".toCharArray()); } finally { instream.close(); } // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "10016225".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 { HttpGet httpget = new HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund"); System.out.println("executing request" + httpget.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpget); try { HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent())); String text; while ((text = bufferedReader.readLine()) != null) { System.out.println(text); } } EntityUtils.consume(entity); } finally { response.close(); } } finally { httpclient.close(); } }
From source file:com.daon.identityx.utils.GenerateAndroidFacet.java
public static void main(String[] args) { String androidKeystoreLocation = System.getProperty("ANDROID_KEYSTORE_LOCATION", DEFAULT_ANDROID_KEYSTORE_LOCATION); String androidKeystorePassword = System.getProperty("ANDROID_KEYSTORE_PASSWORD", DEFAULT_ANDROID_KEYSTORE_PASSWORD); String androidKeystoreCert = System.getProperty("ANDROID_KEYSTORE_CERT_NAME", DEFAULT_ANDROID_KEYSTORE_CERT_NAME); String hashingAlgorithm = System.getProperty("HASHING_ALGORITHM", DEFAULT_HASHING_ALGORITHM); try {// ww w. j a v a 2 s.c o m KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); File filePath = new File(androidKeystoreLocation); if (!filePath.exists()) { System.err.println( "The filepath to the debug keystore could not be located at: " + androidKeystoreCert); System.exit(1); } else { System.out.println("Found the Android Studio keystore at: " + androidKeystoreLocation); } keyStore.load(new FileInputStream(filePath), androidKeystorePassword.toCharArray()); System.out.println("Keystore loaded - password and location were OK"); Certificate cert = keyStore.getCertificate(androidKeystoreCert); if (cert == null) { System.err.println( "Could not location the certification in the store with the name: " + androidKeystoreCert); System.exit(1); } else { System.out.println("Certificate found in the store with name: " + androidKeystoreCert); } byte[] certBytes = cert.getEncoded(); MessageDigest digest = MessageDigest.getInstance(hashingAlgorithm); System.out.println("Hashing algorithm: " + hashingAlgorithm + " found."); byte[] hashedCert = digest.digest(certBytes); String base64HashedCert = Base64.getEncoder().encodeToString(hashedCert); System.out.println("Base64 encoded SHA-1 hash of the certificate: " + base64HashedCert); String base64HashedCertRemoveTrailing = StringUtils.deleteAny(base64HashedCert, "="); System.out.println( "Add the following facet to the Facets file in order for the debug app to be trusted by the FIDO client"); System.out.println("\"android:apk-key-hash:" + base64HashedCertRemoveTrailing + "\""); } catch (Throwable ex) { ex.printStackTrace(); } }
From source file:com.work.common.demo.ClientCustomSSL.java
public final static void main(String[] args) throws Exception { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File("d:\\googlemap.keystore")); try {//from w w w. j a va 2 s .c o m trustStore.load(instream, "111111".toCharArray()); } finally { instream.close(); } // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()) .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 { HttpGet httpget = new HttpGet( "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=500&types=food&name=harbour&sensor=false&key=AIzaSyBR0i9RL44iG8IUx9LcCgxsYOJf6FutQhE"); System.out.println("executing request" + httpget.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpHost, httpget); try { HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); System.out.println(EntityUtils.toString(entity)); } EntityUtils.consume(entity); } finally { response.close(); } } finally { httpclient.close(); } }
From source file:PKCS12Import.java
public static void main(String[] args) throws Exception { if (args.length < 1) { System.err.println("usage: java PKCS12Import {pkcs12file} [newjksfile]"); System.exit(1);/*from w w w . j av a2 s . c o m*/ } File fileIn = new File(args[0]); File fileOut; if (args.length > 1) { fileOut = new File(args[1]); } else { fileOut = new File("newstore.jks"); } if (!fileIn.canRead()) { System.err.println("Unable to access input keystore: " + fileIn.getPath()); System.exit(2); } if (fileOut.exists() && !fileOut.canWrite()) { System.err.println("Output file is not writable: " + fileOut.getPath()); System.exit(2); } KeyStore kspkcs12 = KeyStore.getInstance("pkcs12"); KeyStore ksjks = KeyStore.getInstance("jks"); System.out.print("Enter input keystore passphrase: "); char[] inphrase = readPassphrase(); System.out.print("Enter output keystore passphrase: "); char[] outphrase = readPassphrase(); kspkcs12.load(new FileInputStream(fileIn), inphrase); ksjks.load((fileOut.exists()) ? new FileInputStream(fileOut) : null, outphrase); Enumeration eAliases = kspkcs12.aliases(); int n = 0; while (eAliases.hasMoreElements()) { String strAlias = (String) eAliases.nextElement(); System.err.println("Alias " + n++ + ": " + strAlias); if (kspkcs12.isKeyEntry(strAlias)) { System.err.println("Adding key for alias " + strAlias); Key key = kspkcs12.getKey(strAlias, inphrase); Certificate[] chain = kspkcs12.getCertificateChain(strAlias); ksjks.setKeyEntry(strAlias, key, outphrase, chain); } } OutputStream out = new FileOutputStream(fileOut); ksjks.store(out, outphrase); out.close(); }
From source file:createSod.java
/** * @param args// w w w. j av a2s .co m * @throws CMSException */ public static void main(String[] args) throws Exception { try { CommandLine options = verifyArgs(args); String privateKeyLocation = options.getOptionValue("privatekey"); String keyPassword = options.getOptionValue("keypass"); String certificate = options.getOptionValue("certificate"); String sodContent = options.getOptionValue("content"); String sod = ""; if (options.hasOption("out")) { sod = options.getOptionValue("out"); } // CHARGEMENT DU FICHIER PKCS#12 KeyStore ks = null; char[] password = null; Security.addProvider(new BouncyCastleProvider()); try { ks = KeyStore.getInstance("PKCS12"); // Password pour le fichier personnal_nyal.p12 password = keyPassword.toCharArray(); ks.load(new FileInputStream(privateKeyLocation), password); } catch (Exception e) { System.out.println("Erreur: fichier " + privateKeyLocation + " n'est pas un fichier pkcs#12 valide ou passphrase incorrect"); return; } // RECUPERATION DU COUPLE CLE PRIVEE/PUBLIQUE ET DU CERTIFICAT PUBLIQUE X509Certificate cert = null; PrivateKey privatekey = null; PublicKey publickey = null; try { Enumeration en = ks.aliases(); String ALIAS = ""; Vector vectaliases = new Vector(); while (en.hasMoreElements()) vectaliases.add(en.nextElement()); String[] aliases = (String[]) (vectaliases.toArray(new String[0])); for (int i = 0; i < aliases.length; i++) if (ks.isKeyEntry(aliases[i])) { ALIAS = aliases[i]; break; } privatekey = (PrivateKey) ks.getKey(ALIAS, password); cert = (X509Certificate) ks.getCertificate(ALIAS); publickey = ks.getCertificate(ALIAS).getPublicKey(); } catch (Exception e) { e.printStackTrace(); return; } // Chargement du certificat partir du fichier InputStream inStream = new FileInputStream(certificate); CertificateFactory cf = CertificateFactory.getInstance("X.509"); cert = (X509Certificate) cf.generateCertificate(inStream); inStream.close(); // Chargement du fichier qui va tre sign File file_to_sign = new File(sodContent); byte[] buffer = new byte[(int) file_to_sign.length()]; DataInputStream in = new DataInputStream(new FileInputStream(file_to_sign)); in.readFully(buffer); in.close(); // Chargement des certificats qui seront stocks dans le fichier .p7 // Ici, seulement le certificat personnal_nyal.cer sera associ. // Par contre, la chane des certificats non. ArrayList certList = new ArrayList(); certList.add(cert); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); CMSSignedDataGenerator signGen = new CMSSignedDataGenerator(); // privatekey correspond notre cl prive rcupre du fichier PKCS#12 // cert correspond au certificat publique personnal_nyal.cer // Le dernier argument est l'algorithme de hachage qui sera utilis signGen.addSigner(privatekey, cert, CMSSignedDataGenerator.DIGEST_SHA1); signGen.addCertificatesAndCRLs(certs); CMSProcessable content = new CMSProcessableByteArray(buffer); // Generation du fichier CMS/PKCS#7 // L'argument deux permet de signifier si le document doit tre attach avec la signature // Valeur true: le fichier est attach (c'est le cas ici) // Valeur false: le fichier est dtach CMSSignedData signedData = signGen.generate(content, true, "BC"); byte[] signeddata = signedData.getEncoded(); // Ecriture du buffer dans un fichier. if (sod.equals("")) { System.out.print(signeddata.toString()); } else { FileOutputStream envfos = new FileOutputStream(sod); envfos.write(signeddata); envfos.close(); } } catch (OptionException oe) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(NAME, getOptions()); System.exit(-1); } catch (Exception e) { e.printStackTrace(); return; } }
From source file:com.renren.ntc.sg.util.wxpay.https.ClientCustomSSL.java
public final static void main(String[] args) throws Exception { KeyStore keyStore = KeyStore.getInstance("PKCS12"); FileInputStream instream = new FileInputStream( new File("/Users/allenz/Downloads/wx_cert/apiclient_cert.p12")); try {// w w w. j av a 2 s . c o m keyStore.load(instream, Constants.mch_id.toCharArray()); } finally { instream.close(); } // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, Constants.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 post = new HttpPost("https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers"); System.out.println("executing request" + post.getRequestLine()); String openid = "oQfDLjmZD7Lgynv6vuoBlWXUY_ic"; String nonce_str = Sha1Util.getNonceStr(); String orderId = SUtils.getOrderId(); String re_user_name = "?"; String amount = "1"; String desc = ""; String spbill_create_ip = "123.56.102.224"; String txt = TXT.replace("{mch_appid}", Constants.mch_appid); txt = txt.replace("{mchid}", Constants.mch_id); txt = txt.replace("{openid}", openid); txt = txt.replace("{nonce_str}", nonce_str); txt = txt.replace("{partner_trade_no}", orderId); txt = txt.replace("{check_name}", "FORCE_CHECK"); txt = txt.replace("{re_user_name}", re_user_name); txt = txt.replace("{amount}", amount); txt = txt.replace("{desc}", desc); txt = txt.replace("{spbill_create_ip}", spbill_create_ip); SortedMap<String, String> map = new TreeMap<String, String>(); map.put("mch_appid", Constants.mch_appid); map.put("mchid", Constants.mch_id); map.put("openid", openid); map.put("nonce_str", nonce_str); map.put("partner_trade_no", orderId); //FORCE_CHECK| OPTION_CHECK | NO_CHECK map.put("check_name", "OPTION_CHECK"); map.put("re_user_name", re_user_name); map.put("amount", amount); map.put("desc", desc); map.put("spbill_create_ip", spbill_create_ip); String sign = SUtils.createSign(map).toUpperCase(); txt = txt.replace("{sign}", sign); post.setEntity(new StringEntity(txt, "utf-8")); CloseableHttpResponse response = httpclient.execute(post); try { HttpEntity entity = response.getEntity(); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent())); String text; StringBuffer sb = new StringBuffer(); while ((text = bufferedReader.readLine()) != null) { sb.append(text); } String resp = sb.toString(); LoggerUtils.getInstance().log(String.format("req %s rec %s", txt, resp)); if (isOk(resp)) { String payment_no = getValue(resp, "payment_no"); LoggerUtils.getInstance() .log(String.format("order %s pay OK payment_no %s", orderId, payment_no)); } } EntityUtils.consume(entity); } finally { response.close(); } } finally { httpclient.close(); } }
From source file:pt.ua.tm.neji.web.test.TestREST.java
public static void main(String[] args) throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null);/*from ww w . j a v a2 s . co m*/ MySSLSocketFactory 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, "utf-8"); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 8010)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); String url = "https://localhost:8010/annotate/default/export?tool=becas-webapp&email=bioinformatics@ua.pt"; // POST CloseableHttpClient client = new DefaultHttpClient(ccm, params); HttpPost post = new HttpPost(url); //post.setHeader("Content-Type", "application/json"); List<NameValuePair> keyValuesPairs = new ArrayList(); //keyValuesPairs.add(new BasicNameValuePair("format", "neji")); keyValuesPairs.add(new BasicNameValuePair("fromFile", "false")); //keyValuesPairs.add(new BasicNameValuePair("groups", "{\"DISO\":true,\"ANAT\":true}")); //keyValuesPairs.add(new BasicNameValuePair("groups", "{}")); //keyValuesPairs.add(new BasicNameValuePair("groups", "{\"DISO\":true}")); //keyValuesPairs.add(new BasicNameValuePair("groups", "{\"ANAT\":true}")); keyValuesPairs.add(new BasicNameValuePair("text", text)); keyValuesPairs.add(new BasicNameValuePair("crlf", "false")); post.setEntity(new UrlEncodedFormEntity(keyValuesPairs)); HttpResponse response = client.execute(post); String result = IOUtils.toString(response.getEntity().getContent()); System.out.println(result); }
From source file:com.adhi.webserver.WebServer.java
public static void main(String[] args) throws Exception { int port = 9999; // Set up the HTTP protocol processor HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate()) .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl()) .build();//from w w w . ja v a2s. c o m // Set up request handlers UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); reqistry.register("*", new MessageCommandHandler()); // Set up the HTTP service HttpService httpService = new HttpService(httpproc, reqistry); SSLServerSocketFactory sf = null; if (port == 8443) { // Initialize SSL context ClassLoader cl = WebServer.class.getClassLoader(); URL url = cl.getResource("my.keystore"); if (url == null) { System.out.println("Keystore not found"); System.exit(1); } KeyStore keystore = KeyStore.getInstance("jks"); keystore.load(url.openStream(), "secret".toCharArray()); KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keystore, "secret".toCharArray()); KeyManager[] keymanagers = kmfactory.getKeyManagers(); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(keymanagers, null, null); sf = sslcontext.getServerSocketFactory(); } Thread t = new RequestListenerThread(port, httpService, sf); t.setDaemon(false); t.start(); }
From source file:ch.swisscom.mid.verifier.MobileIdCmsVerifier.java
public static void main(String[] args) { if (args == null || args.length < 1) { System.out.println("Usage: ch.swisscom.mid.verifier.MobileIdCmsVerifier [OPTIONS]"); System.out.println();/* www. j a va2s .c o m*/ System.out.println("Options:"); System.out.println( " -cms=VALUE or -stdin - base64 encoded CMS/PKCS7 signature string, either as VALUE or via standard input"); System.out.println( " -jks=VALUE - optional path to truststore file (default is 'jks/truststore.jks')"); System.out.println(" -jkspwd=VALUE - optional truststore password (default is 'secret')"); System.out.println(); System.out.println("Example:"); System.out.println(" java ch.swisscom.mid.verifier.MobileIdCmsVerifier -cms=MIII..."); System.out.println(" echo -n MIII... | java ch.swisscom.mid.verifier.MobileIdCmsVerifier -stdin"); System.exit(1); } try { MobileIdCmsVerifier verifier = null; String jks = "jks/truststore.jks"; String jkspwd = "secret"; String param; for (int i = 0; i < args.length; i++) { param = args[i].toLowerCase(); if (param.contains("-jks=")) { jks = args[i].substring(args[i].indexOf("=") + 1).trim(); } else if (param.contains("-jkspwd=")) { jkspwd = args[i].substring(args[i].indexOf("=") + 1).trim(); } else if (param.contains("-cms=")) { verifier = new MobileIdCmsVerifier(args[i].substring(args[i].indexOf("=") + 1).trim()); } else if (param.contains("-stdin")) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String stdin; if ((stdin = in.readLine()) != null && stdin.length() != 0) verifier = new MobileIdCmsVerifier(stdin.trim()); } } KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream(jks), jkspwd.toCharArray()); // If you are behind a Proxy.. // System.setProperty("proxyHost", "10.185.32.54"); // System.setProperty("proxyPort", "8079"); // or set it via VM arguments: -DproxySet=true -DproxyHost=10.185.32.54 -DproxyPort=8079 // Print Issuer/SubjectDN/SerialNumber of all x509 certificates that can be found in the CMSSignedData verifier.printAllX509Certificates(); // Print Signer's X509 Certificate Details System.out.println("X509 SignerCert SerialNumber: " + verifier.getX509SerialNumber()); System.out.println("X509 SignerCert Issuer: " + verifier.getX509IssuerDN()); System.out.println("X509 SignerCert Subject DN: " + verifier.getX509SubjectDN()); System.out.println("X509 SignerCert Validity Not Before: " + verifier.getX509NotBefore()); System.out.println("X509 SignerCert Validity Not After: " + verifier.getX509NotAfter()); System.out.println("X509 SignerCert Validity currently valid: " + verifier.isCertCurrentlyValid()); System.out.println("User's unique Mobile ID SerialNumber: " + verifier.getMIDSerialNumber()); // Print signed content (should be equal to the DTBS Message of the Signature Request) System.out.println("Signed Data: " + verifier.getSignedData()); // Verify the signature on the SignerInformation object System.out.println("Signature Valid: " + verifier.isVerified()); // Validate certificate path against trust anchor incl. OCSP revocation check System.out.println("X509 SignerCert Valid (Path+OCSP): " + verifier.isCertValid(keyStore)); } catch (Exception e) { e.printStackTrace(); } }