List of usage examples for java.security KeyStore getDefaultType
public static final String getDefaultType()
From source file:edu.internet2.middleware.subject.provider.LdapPEMSocketFactory.java
protected void initManagers() { // trust managers try {/*from ww w . j av a 2 s . c om*/ X509Certificate cert = null; if (caFilename != null) cert = readCertificate(caFilename); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null, null); ks.setCertificateEntry("CACERT", cert); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); trustManagers = tmf.getTrustManagers(); } catch (Exception e) { log.error("ldap source cacert error: " + e); } // key managers if (certFilename != null && keyFilename != null) { char[] pw = new char[] { 0 }; try { X509Certificate cert = readCertificate(certFilename); PKCS1 pkcs = new PKCS1(); PrivateKey key = pkcs.readKey(keyFilename); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null, null); X509Certificate[] chain = new X509Certificate[1]; chain[0] = cert; ks.setKeyEntry("CERT", (Key) key, pw, chain); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, pw); keyManagers = kmf.getKeyManagers(); } catch (Exception e) { log.error("ldap source cert/key error: " + e); } } }
From source file:org.openiot.gsn.http.ac.GSNClient.java
public GSNClient(String host, int gsnhttpport, int gsnhttpsport) { this.host = host; this.gsnhttpport = gsnhttpport; this.gsnhttpsport = gsnhttpsport; httpclient = new DefaultHttpClient(); FileInputStream instream = null; try {//from w w w. j a va 2 s .c o m this.trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); instream = new FileInputStream(new File("conf/clienttestkeystore")); this.trustStore.load(instream, "changeit".toCharArray()); SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore); socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme sch = new Scheme("https", socketFactory, gsnhttpsport); Scheme plainsch = new Scheme("http", PlainSocketFactory.getSocketFactory(), gsnhttpport); httpclient.getConnectionManager().getSchemeRegistry().register(sch); httpclient.getConnectionManager().getSchemeRegistry().register(plainsch); } catch (KeyStoreException e) { logger.error("ERROR IN GSNCLIENT : Exception while creating trustStore :"); logger.error(e.getMessage(), e); } catch (FileNotFoundException e) { logger.error("ERROR IN GSNCLIENT : FileInputStream exception :"); logger.error(e.getMessage(), e); } catch (Exception e) { logger.error("ERROR IN GSNCLIENT : Exception while loading truststore :"); logger.error(e.getMessage(), e); } finally { try { if (instream != null) { instream.close(); } } catch (Exception e) { } } }
From source file:com.shwy.bestjoy.utils.AndroidHttpClient.java
/** * Create a new HttpClient with reasonable defaults (which you can update). * * @param userAgent to report in your HTTP requests. * @return AndroidHttpClient for you to use for all your requests. *///from w w w .jav a 2 s . com public static HttpClient newInstance(String userAgent) { try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sslSocketFactory = new SSLSocketFactoryEx(trustStore); sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); // Turn off stale checking. Our connections break all the time anyway, // and it's not worth it to pay the penalty of checking every time. HttpConnectionParams.setStaleCheckingEnabled(params, false); // Default connection and socket timeout of 20 seconds. Tweak to taste. HttpConnectionParams.setConnectionTimeout(params, 60 * 1000); HttpConnectionParams.setSoTimeout(params, 60 * 1000); HttpConnectionParams.setSocketBufferSize(params, 8192); // Don't handle redirects -- return them to the caller. Our code // often wants to re-POST after a redirect, which we must do ourselves. HttpClientParams.setRedirecting(params, true); // Set the specified user agent and register standard protocols. HttpProtocolParams.setUserAgent(params, userAgent); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", sslSocketFactory, 443)); ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry); // We use a factory method to modify superclass initialization // parameters without the funny call-a-static-method dance. return new AndroidHttpClient(manager, params); } catch (KeyStoreException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (UnrecoverableKeyException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } return new DefaultHttpClient(); }
From source file:biz.mosil.webtools.MosilSSLSocketFactory.java
public static HttpClient getHttpClient(HttpParams _params) { try {// w ww . j a v a 2 s . c o m KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory factory = new MosilSSLSocketFactory(trustStore); factory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpProtocolParams.setVersion(_params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(_params, HTTP.UTF_8); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), MosilWebConf.HTTP_PORT)); registry.register(new Scheme("https", factory, MosilWebConf.SSL_PORT)); ClientConnectionManager clientConnectionManager = new ThreadSafeClientConnManager(_params, registry); return new DefaultHttpClient(clientConnectionManager, _params); } catch (Exception _ex) { return new DefaultHttpClient(); } }
From source file:de.betterform.connector.http.ssl.BetterFORMKeyStoreManager.java
private X509KeyManager getCustomX509KeyManager(final URL url, final String password) throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException { KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); if (url == null) { throw new IllegalArgumentException("BetterFORMKeyStoreManager: Keystore url may not be null"); }/* w ww .j av a2 s . c o m*/ LOGGER.debug("BetterFORMKeyStoreManager: initializing custom key store"); KeyStore customKeystore = KeyStore.getInstance(KeyStore.getDefaultType()); InputStream is = null; try { is = url.openStream(); customKeystore.load(is, password != null ? password.toCharArray() : null); } finally { if (is != null) is.close(); } if (LOGGER.isTraceEnabled()) { Enumeration aliases = customKeystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); LOGGER.trace("Trusted certificate '" + alias + "':"); Certificate trustedcert = customKeystore.getCertificate(alias); if (trustedcert != null && trustedcert instanceof X509Certificate) { X509Certificate cert = (X509Certificate) trustedcert; LOGGER.trace(" Subject DN: " + cert.getSubjectDN()); LOGGER.trace(" Signature Algorithm: " + cert.getSigAlgName()); LOGGER.trace(" Valid from: " + cert.getNotBefore()); LOGGER.trace(" Valid until: " + cert.getNotAfter()); LOGGER.trace(" Issuer: " + cert.getIssuerDN()); } } } keyManagerFactory.init(customKeystore, password.toCharArray()); KeyManager[] customX509KeyManagers = keyManagerFactory.getKeyManagers(); if (customX509KeyManagers != null && customX509KeyManagers.length > 0) { for (int i = 0; i < customX509KeyManagers.length; i++) { if (customX509KeyManagers[i] instanceof X509KeyManager) { return (X509KeyManager) customX509KeyManagers[i]; } } } return null; }
From source file:com.collabnet.tracker.common.httpClient.SslProtocolSocketFactory.java
private SslProtocolSocketFactory() { KeyManager[] keymanagers = null; if (System.getProperty(KEY_STORE) != null && System.getProperty(KEY_STORE_PASSWORD) != null) { try {/*from w w w . ja va 2 s . com*/ String type = System.getProperty(KEY_STORE_TYPE, KeyStore.getDefaultType()); KeyStore keyStore = KeyStore.getInstance(type); char[] password = System.getProperty(KEY_STORE_PASSWORD).toCharArray(); FileInputStream keyStoreInputStream = new FileInputStream(System.getProperty(KEY_STORE)); keyStore.load(keyStoreInputStream, password); keyStoreInputStream.close(); KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, password); keymanagers = keyManagerFactory.getKeyManagers(); } catch (Exception e) { log(0, "Could not initialize keystore", e); } } hasKeyManager = keymanagers != null; try { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(keymanagers, new TrustManager[] { new TrustAllTrustManager() }, null); this.socketFactory = sslContext.getSocketFactory(); } catch (Exception e) { log(0, "Could not initialize SSL context", e); } }
From source file:org.syslog_ng.elasticsearch_v2.client.http.ESHttpsClient.java
private KeyStore createKeyStore() { KeyStore keyStore;// w ww.j a v a 2 s . c om try { keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); } catch (KeyStoreException e) { throw new ESHttpsClient.HttpClientBuilderException("Error initializing keyStore", e); } return keyStore; }
From source file:org.apache.ranger.authorization.kafka.authorizer.KafkaRangerAuthorizerSASLSSLTest.java
@org.junit.BeforeClass public static void setup() throws Exception { // JAAS Config file String basedir = System.getProperty("basedir"); if (basedir == null) { basedir = new File(".").getCanonicalPath(); }//from w w w. java 2 s . com File f = new File(basedir + "/src/test/resources/kafka_plain.jaas"); System.setProperty("java.security.auth.login.config", f.getPath()); // Create keys String serviceDN = "CN=Service,O=Apache,L=Dublin,ST=Leinster,C=IE"; String clientDN = "CN=Client,O=Apache,L=Dublin,ST=Leinster,C=IE"; // Create a truststore KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(null, "security".toCharArray()); serviceKeystorePath = KafkaTestUtils.createAndStoreKey(serviceDN, serviceDN, BigInteger.valueOf(30), "sspass", "myservicekey", "skpass", keystore); clientKeystorePath = KafkaTestUtils.createAndStoreKey(clientDN, clientDN, BigInteger.valueOf(31), "cspass", "myclientkey", "ckpass", keystore); File truststoreFile = File.createTempFile("kafkatruststore", ".jks"); try (OutputStream output = new FileOutputStream(truststoreFile)) { keystore.store(output, "security".toCharArray()); } truststorePath = truststoreFile.getPath(); zkServer = new TestingServer(); // Get a random port ServerSocket serverSocket = new ServerSocket(0); port = serverSocket.getLocalPort(); serverSocket.close(); final Properties props = new Properties(); props.put("broker.id", 1); props.put("host.name", "localhost"); props.put("port", port); props.put("log.dir", "/tmp/kafka"); props.put("zookeeper.connect", zkServer.getConnectString()); props.put("replica.socket.timeout.ms", "1500"); props.put("controlled.shutdown.enable", Boolean.TRUE.toString()); // Enable SASL_SSL props.put("listeners", "SASL_SSL://localhost:" + port); props.put("security.inter.broker.protocol", "SASL_SSL"); props.put("sasl.enabled.mechanisms", "PLAIN"); props.put("sasl.mechanism.inter.broker.protocol", "PLAIN"); props.put("ssl.keystore.location", serviceKeystorePath); props.put("ssl.keystore.password", "sspass"); props.put("ssl.key.password", "skpass"); props.put("ssl.truststore.location", truststorePath); props.put("ssl.truststore.password", "security"); // Plug in Apache Ranger authorizer props.put("authorizer.class.name", "org.apache.ranger.authorization.kafka.authorizer.RangerKafkaAuthorizer"); // Create users for testing UserGroupInformation.createUserForTesting("alice", new String[] { "IT" }); KafkaConfig config = new KafkaConfig(props); kafkaServer = new KafkaServerStartable(config); kafkaServer.startup(); // Create some topics ZkClient zkClient = new ZkClient(zkServer.getConnectString(), 30000, 30000, ZKStringSerializer$.MODULE$); final ZkUtils zkUtils = new ZkUtils(zkClient, new ZkConnection(zkServer.getConnectString()), false); AdminUtils.createTopic(zkUtils, "test", 1, 1, new Properties(), RackAwareMode.Enforced$.MODULE$); AdminUtils.createTopic(zkUtils, "dev", 1, 1, new Properties(), RackAwareMode.Enforced$.MODULE$); }
From source file:org.commonjava.util.jhttpc.INTERNAL.util.SSLUtils.java
public static KeyStore decodePEMTrustStore(final String pemContent, final String aliasPrefix) throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException { Logger logger = LoggerFactory.getLogger(SSLUtils.class); final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null);/*from www .ja v a 2s . c o m*/ final CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); final List<String> lines = readLines(pemContent); final StringBuilder current = new StringBuilder(); final List<String> entries = new ArrayList<String>(); for (String line : lines) { if (line == null) { continue; } if (line.startsWith("-----BEGIN")) { current.setLength(0); } else if (line.startsWith("-----END")) { entries.add(current.toString()); } else { current.append(line); } } logger.trace("Found {} entries to decode.", entries.size()); int i = 0; for (final String entry : entries) { logger.trace("Decoding certificate info from:\n\n{}\n\n", entry); final byte[] data = decodeBase64(entry); final Certificate c = certFactory.generateCertificate(new ByteArrayInputStream(data)); X509Certificate cert = (X509Certificate) c; Set<String> aliases = new HashSet<String>(); if (i < 1) { aliases.add(aliasPrefix); } else { aliases.add(aliasPrefix + i); } extractAliases(cert, aliases); KeyStore.TrustedCertificateEntry ksEntry = new KeyStore.TrustedCertificateEntry(cert); for (String alias : aliases) { ks.setEntry(alias, ksEntry, null); logger.trace("Storing trusted cert under alias: {}\n with DN: {}", alias, cert.getSubjectDN().getName()); } logger.trace("Certificate added."); i++; } return ks; }
From source file:com.emc.cto.ridagent.rid.test.TestScript.java
public static String httpSend(String output, String destURL) throws ParserConfigurationException, SAXException { /* Set up TLS mutual authentication */ KeyStore keystore = null;/*from ww w.jav a 2 s .c o m*/ String docid = null; try { keystore = KeyStore.getInstance(KeyStore.getDefaultType()); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } InputStream keystoreInput = null; try { keystoreInput = new FileInputStream(m_keystorePath); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { keystore.load(keystoreInput, m_keystorePassword.toCharArray()); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if (logger.isDebugEnabled()) { logger.debug("Keystore has " + keystore.size() + " keys"); } } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } KeyStore truststore = null; try { truststore = KeyStore.getInstance(KeyStore.getDefaultType()); } catch (KeyStoreException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } InputStream truststoreInput = null; try { truststoreInput = new FileInputStream(m_truststorePath); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { truststore.load(truststoreInput, m_truststorePassword.toCharArray()); } catch (NoSuchAlgorithmException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (CertificateException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } SchemeRegistry schemeRegistry = new SchemeRegistry(); SSLSocketFactory schemeSocketFactory = null; try { schemeSocketFactory = new SSLSocketFactory(keystore, m_keystorePassword, truststore); } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnrecoverableKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } schemeRegistry.register(new Scheme(m_protocol, m_port, schemeSocketFactory)); final HttpParams httpParams = new BasicHttpParams(); DefaultHttpClient httpClient = new DefaultHttpClient(new BasicClientConnectionManager(schemeRegistry), httpParams); /* Prepare the request to send */ Map<String, Object> responseMap = new HashMap<String, Object>(); HttpEntity request = new StringEntity(output, ContentType.TEXT_XML); //Create POST method HttpPost postMethod = new HttpPost(destURL); postMethod.setHeader("User-Agent", "EMC RID System"); postMethod.setHeader("Content-Type", "text/xml"); postMethod.setEntity(request); /* POST the request and process the response */ HttpResponse httpResponse = null; int code; try { httpResponse = httpClient.execute(postMethod); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (httpResponse.getEntity() != null) { code = httpResponse.getStatusLine().getStatusCode(); try { InputStream xml = httpResponse.getEntity().getContent(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(xml); docid = doc.getElementsByTagName("iodef:IncidentID").item(0).getTextContent(); System.out.println("ID of the newly created document " + docid); } catch (ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } responseMap.put("success", true); responseMap.put("statusCode", code); } else { responseMap.put("success", false); responseMap.put("errorMessage", "Send failed (fill in exception)"); } return docid; }