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.tc.simple.apn.quicktests.Test.java
/** * @param args/*from ww w . java 2 s . com*/ */ public static void main(String[] args) { SSLSocket socket = null; try { String host = "gateway.sandbox.push.apple.com"; int port = 2195; String token = "de7f197546e41a76684f8e2d89f397ed165298d7772f4bd9b0f39c674b185b0f"; System.out.println(token.toCharArray().length); //String token = "8cebc7c08f79fa62f0994eb4298387ff930857ff8d14a50de431559cf476b223"; KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(Test.class.getResourceAsStream("egram-dev-apn.p12"), "xxxxxxxxx".toCharArray()); KeyManagerFactory keyMgrFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyMgrFactory.init(keyStore, "xxxxxxxxx".toCharArray()); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyMgrFactory.getKeyManagers(), null, null); SSLSocketFactory socketFactory = sslContext.getSocketFactory(); socket = (SSLSocket) socketFactory.createSocket(host, port); String[] cipherSuites = socket.getSupportedCipherSuites(); socket.setEnabledCipherSuites(cipherSuites); socket.startHandshake(); char[] t = token.toCharArray(); byte[] b = Hex.decodeHex(t); OutputStream outputstream = socket.getOutputStream(); String payload = "{\"aps\":{\"alert\":\"yabadabadooo\"}}"; int expiry = (int) ((System.currentTimeMillis() / 1000L) + 7200); ByteArrayOutputStream bout = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bout); //command dos.writeByte(1); //id dos.writeInt(900); //expiry dos.writeInt(expiry); //token length. dos.writeShort(b.length); //token dos.write(b); //payload length dos.writeShort(payload.length()); //payload. dos.write(payload.getBytes()); byte[] byteMe = bout.toByteArray(); socket.getOutputStream().write(byteMe); socket.setSoTimeout(900); InputStream in = socket.getInputStream(); System.out.println(APNErrors.getError(in.read())); in.close(); outputstream.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
From source file:com.boonya.http.async.examples.nio.client.AsyncClientCustomSSL.java
public final static void main(String[] args) throws Exception { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File("my.keystore")); try {// w ww . ja v a 2 s.com trustStore.load(instream, "nopassword".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 SSLIOSessionStrategy sslSessionStrategy = new SSLIOSessionStrategy(sslcontext, new String[] { "TLSv1" }, null, SSLIOSessionStrategy.getDefaultHostnameVerifier()); CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setSSLStrategy(sslSessionStrategy).build(); try { httpclient.start(); HttpGet request = new HttpGet("https://issues.apache.org/"); Future<HttpResponse> future = httpclient.execute(request, null); HttpResponse response = future.get(); System.out.println("Response: " + response.getStatusLine()); System.out.println("Shutting down"); } finally { httpclient.close(); } System.out.println("Done"); }
From source file:com.hilatest.httpclient.apacheexample.ClientCustomSSL.java
public final static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File("my.keystore")); try {/*from ww w . j av a2s. c o m*/ trustStore.load(instream, "nopassword".toCharArray()); } finally { instream.close(); } SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore); Scheme sch = new Scheme("https", socketFactory, 443); httpclient.getConnectionManager().getSchemeRegistry().register(sch); HttpGet httpget = new HttpGet("https://localhost/"); System.out.println("executing request" + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } if (entity != null) { entity.consumeContent(); } // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); }
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 ww w . j av a 2s.c om*/ 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.lxf.spider.client.ClientCustomSSL.java
public final static void main(String[] args) throws Exception { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File("my.keystore")); try {//from ww w . j a v a2 s . c o m trustStore.load(instream, "nopassword".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://localhost/"); 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()); } EntityUtils.consume(entity); } finally { response.close(); } } finally { httpclient.close(); } }
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 {/*from w ww.ja v a2 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.wxpay.ClientCustomSSL.java
public final static void main(String[] args) throws Exception { KeyStore keyStore = KeyStore.getInstance("PKCS12"); FileInputStream instream = new FileInputStream(new File("E:/apiclient_cert1.p12")); try {/*from w ww.j a v a 2s .c o m*/ keyStore.load(instream, "1269885501".toCharArray()); } finally { instream.close(); } // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "1269885501".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:TestSign.java
/** * Method main// w ww . j a v a 2 s . c o m * * @param unused * @throws Exception */ public static void main(String unused[]) throws Exception { //J- String keystoreType = "JKS"; String keystoreFile = "data/org/apache/xml/security/samples/input/keystore.jks"; String keystorePass = "xmlsecurity"; String privateKeyAlias = "test"; String privateKeyPass = "xmlsecurity"; String certificateAlias = "test"; File signatureFile = new File("signature.xml"); //J+ KeyStore ks = KeyStore.getInstance(keystoreType); FileInputStream fis = new FileInputStream(keystoreFile); ks.load(fis, keystorePass.toCharArray()); PrivateKey privateKey = (PrivateKey) ks.getKey(privateKeyAlias, privateKeyPass.toCharArray()); javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder(); org.w3c.dom.Document doc = db.newDocument(); String BaseURI = signatureFile.toURL().toString(); XMLSignature sig = new XMLSignature(doc, BaseURI, XMLSignature.ALGO_ID_SIGNATURE_DSA); doc.appendChild(sig.getElement()); { ObjectContainer obj = new ObjectContainer(doc); Element anElement = doc.createElementNS(null, "InsideObject"); anElement.appendChild(doc.createTextNode("A text in a box")); obj.appendChild(anElement); String Id = "TheFirstObject"; obj.setId(Id); sig.appendObject(obj); Transforms transforms = new Transforms(doc); transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS); sig.addDocument("#" + Id, transforms, Constants.ALGO_ID_DIGEST_SHA1); } { X509Certificate cert = (X509Certificate) ks.getCertificate(certificateAlias); sig.addKeyInfo(cert); sig.addKeyInfo(cert.getPublicKey()); System.out.println("Start signing"); sig.sign(privateKey); System.out.println("Finished signing"); } FileOutputStream f = new FileOutputStream(signatureFile); XMLUtils.outputDOMc14nWithComments(doc, f); f.close(); System.out.println("Wrote signature to " + BaseURI); for (int i = 0; i < sig.getSignedInfo().getSignedContentLength(); i++) { System.out.println("--- Signed Content follows ---"); System.out.println(new String(sig.getSignedInfo().getSignedContentItem(i))); } }
From source file:ImportKey.java
/** * <p>//from w w w. jav a 2 s . co m * Takes two file names for a key and the certificate for the key, and * imports those into a keystore. Optionally it takes an alias for the key. * <p> * The first argument is the filename for the key. The key should be in * PKCS8-format. * <p> * The second argument is the filename for the certificate for the key. * <p> * If a third argument is given it is used as the alias. If missing, the key * is imported with the alias importkey * <p> * The name of the keystore file can be controlled by setting the keystore * property (java -Dkeystore=mykeystore). If no name is given, the file is * named <code>keystore.ImportKey</code> and placed in your home directory. * * @param args * [0] Name of the key file, [1] Name of the certificate file [2] * Alias for the key. **/ public static void main(String args[]) { // change this if you want another password by default String keypass = "password"; // change this if you want another alias by default String defaultalias = "tomcat"; // change this if you want another keystorefile by default String keystorename = null; // parsing command line input String keyfile = ""; String certfile = ""; if (args.length < 3 || args.length > 4) { System.out.println("Usage: java comu.ImportKey keystore keyfile certfile [alias]"); System.exit(0); } else { keystorename = args[0]; keyfile = args[1]; certfile = args[2]; if (args.length > 3) defaultalias = args[3]; } try { // initializing and clearing keystore KeyStore ks = KeyStore.getInstance("JKS", "SUN"); ks.load(null, keypass.toCharArray()); System.out.println("Using keystore-file : " + keystorename); ks.store(new FileOutputStream(keystorename), keypass.toCharArray()); ks.load(new FileInputStream(keystorename), keypass.toCharArray()); // loading Key InputStream fl = fullStream(keyfile); byte[] key = new byte[fl.available()]; KeyFactory kf = KeyFactory.getInstance("RSA"); fl.read(key, 0, fl.available()); fl.close(); PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(key); PrivateKey ff = kf.generatePrivate(keysp); // loading CertificateChain CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream certstream = fullStream(certfile); Collection c = cf.generateCertificates(certstream); Certificate[] certs = new Certificate[c.toArray().length]; if (c.size() == 1) { certstream = fullStream(certfile); System.out.println("One certificate, no chain."); Certificate cert = cf.generateCertificate(certstream); certs[0] = cert; } else { System.out.println("Certificate chain length: " + c.size()); certs = (Certificate[]) c.toArray(new Certificate[c.size()]); } // storing keystore ks.setKeyEntry(defaultalias, ff, keypass.toCharArray(), certs); System.out.println("Key and certificate stored."); System.out.println("Alias:" + defaultalias + " Password:" + keypass); ks.store(new FileOutputStream(keystorename), keypass.toCharArray()); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:CertificateSigner.java
public static void main(String[] args) { String ksname = null; // the keystore name String alias = null; // the private key alias String inname = null; // the input file name String outname = null; // the output file name for (int i = 0; i < args.length; i += 2) { if (args[i].equals("-keystore")) ksname = args[i + 1];//from w w w . j av a 2s . c o m else if (args[i].equals("-alias")) alias = args[i + 1]; else if (args[i].equals("-infile")) inname = args[i + 1]; else if (args[i].equals("-outfile")) outname = args[i + 1]; else usage(); } if (ksname == null || alias == null || inname == null || outname == null) usage(); try { Console console = System.console(); if (console == null) error("No console"); char[] password = console.readPassword("Keystore password: "); KeyStore store = KeyStore.getInstance("JKS", "SUN"); InputStream in = new FileInputStream(ksname); store.load(in, password); Arrays.fill(password, ' '); in.close(); char[] keyPassword = console.readPassword("Key password for %s: ", alias); PrivateKey issuerPrivateKey = (PrivateKey) store.getKey(alias, keyPassword); Arrays.fill(keyPassword, ' '); if (issuerPrivateKey == null) error("No such private key"); in = new FileInputStream(inname); CertificateFactory factory = CertificateFactory.getInstance("X.509"); X509Certificate inCert = (X509Certificate) factory.generateCertificate(in); in.close(); byte[] inCertBytes = inCert.getTBSCertificate(); X509Certificate issuerCert = (X509Certificate) store.getCertificate(alias); Principal issuer = issuerCert.getSubjectDN(); String issuerSigAlg = issuerCert.getSigAlgName(); FileOutputStream out = new FileOutputStream(outname); X509CertInfo info = new X509CertInfo(inCertBytes); info.set(X509CertInfo.ISSUER, new CertificateIssuerName((X500Name) issuer)); X509CertImpl outCert = new X509CertImpl(info); outCert.sign(issuerPrivateKey, issuerSigAlg); outCert.derEncode(out); out.close(); } catch (Exception e) { e.printStackTrace(); } }