List of usage examples for java.security KeyStore getDefaultType
public static final String getDefaultType()
From source file:com.zrlh.llkc.funciton.Http_Utility.java
public static HttpClient getNewHttpClient(Context context) { try {/*from w w w . jav a2 s . co 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, 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, Http_Utility.SET_CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(params, Http_Utility.SET_SOCKET_TIMEOUT); HttpClient client = new DefaultHttpClient(ccm, params); WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo info = wifiManager.getConnectionInfo(); if (!wifiManager.isWifiEnabled() || -1 == info.getNetworkId()) { // ??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:net.jimj.automaton.Bot.java
private void connect() { LOGGER.debug("Connecting..."); try {// w w w . ja va2 s . c o m SSLContext ctx = null; if (StringUtils.isNotBlank(config.getIrcKeystoreLocation())) { SSLContextBuilder ctxBuilder = SSLContexts.custom(); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); try (FileInputStream keyInStream = new FileInputStream( new File(config.getIrcKeystoreLocation()));) { trustStore.load(keyInStream, config.getIrcKeystorePassword().toCharArray()); } ctxBuilder.loadTrustMaterial(trustStore); ctx = ctxBuilder.build(); } IRCConnection.Builder connectionBuilder = IRCConnection.builder().withHost(config.getServer()) .withNick(config.getNick()); if (config.getPort() != -1) { connectionBuilder = connectionBuilder.withPort(config.getPort()).withSSLContext(ctx); } IRCConnection ircConnection = connectionBuilder.withListener(this).build(); ircConnection.connect(); ircClient = new IRCClient(ircConnection); } catch (Exception e) { LOGGER.error("Exception in go method ", e); } }
From source file:org.apache.ws.security.components.crypto.Merlin.java
public void loadProperties(Properties properties, ClassLoader loader) throws CredentialException, IOException { if (properties == null) { return;/*from ww w .jav a 2s.c o m*/ } this.properties = properties; // // Load the provider(s) // String provider = properties.getProperty(CRYPTO_KEYSTORE_PROVIDER); if (provider != null) { provider = provider.trim(); } String certProvider = properties.getProperty(CRYPTO_CERT_PROVIDER); if (certProvider != null) { setCryptoProvider(certProvider); } // // Load the KeyStore // String alias = properties.getProperty(KEYSTORE_ALIAS); if (alias != null) { alias = alias.trim(); defaultAlias = alias; } String keyStoreLocation = properties.getProperty(KEYSTORE_FILE); if (keyStoreLocation == null) { keyStoreLocation = properties.getProperty(OLD_KEYSTORE_FILE); } if (keyStoreLocation != null) { keyStoreLocation = keyStoreLocation.trim(); InputStream is = loadInputStream(loader, keyStoreLocation); try { String passwd = properties.getProperty(KEYSTORE_PASSWORD, "security"); if (passwd != null) { passwd = passwd.trim(); } String type = properties.getProperty(KEYSTORE_TYPE, KeyStore.getDefaultType()); if (type != null) { type = type.trim(); } keystore = load(is, passwd, provider, type); if (DO_DEBUG) { LOG.debug("The KeyStore " + keyStoreLocation + " of type " + type + " has been loaded"); } String privatePasswd = properties.getProperty(KEYSTORE_PRIVATE_PASSWORD); if (privatePasswd != null) { privatePasswordSet = true; } } finally { if (is != null) { is.close(); } } } else { if (DO_DEBUG) { LOG.debug("The KeyStore is not loaded as KEYSTORE_FILE is null"); } } // // Load the TrustStore // String trustStoreLocation = properties.getProperty(TRUSTSTORE_FILE); if (trustStoreLocation != null) { trustStoreLocation = trustStoreLocation.trim(); InputStream is = loadInputStream(loader, trustStoreLocation); try { String passwd = properties.getProperty(TRUSTSTORE_PASSWORD, "changeit"); if (passwd != null) { passwd = passwd.trim(); } String type = properties.getProperty(TRUSTSTORE_TYPE, KeyStore.getDefaultType()); if (type != null) { type = type.trim(); } truststore = load(is, passwd, provider, type); if (DO_DEBUG) { LOG.debug("The TrustStore " + trustStoreLocation + " of type " + type + " has been loaded"); } loadCACerts = false; } finally { if (is != null) { is.close(); } } } else { String loadCacerts = properties.getProperty(LOAD_CA_CERTS, "false"); if (loadCacerts != null) { loadCacerts = loadCacerts.trim(); } if (Boolean.valueOf(loadCacerts).booleanValue()) { String cacertsPath = System.getProperty("java.home") + "/lib/security/cacerts"; if (cacertsPath != null) { cacertsPath = cacertsPath.trim(); } InputStream is = new FileInputStream(cacertsPath); try { String cacertsPasswd = properties.getProperty(TRUSTSTORE_PASSWORD, "changeit"); if (cacertsPasswd != null) { cacertsPasswd = cacertsPasswd.trim(); } truststore = load(is, cacertsPasswd, null, KeyStore.getDefaultType()); if (DO_DEBUG) { LOG.debug("CA certs have been loaded"); } loadCACerts = true; } finally { if (is != null) { is.close(); } } } } // // Load the CRL file // String crlLocation = properties.getProperty(X509_CRL_FILE); if (crlLocation != null) { crlLocation = crlLocation.trim(); InputStream is = loadInputStream(loader, crlLocation); try { CertificateFactory cf = getCertificateFactory(); X509CRL crl = (X509CRL) cf.generateCRL(is); if (provider == null || provider.length() == 0) { crlCertStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(Collections.singletonList(crl))); } else { crlCertStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(Collections.singletonList(crl)), provider); } if (DO_DEBUG) { LOG.debug("The CRL " + crlLocation + " has been loaded"); } } catch (Exception e) { if (DO_DEBUG) { LOG.debug(e.getMessage(), e); } throw new CredentialException(CredentialException.IO_ERROR, "ioError00", e); } finally { if (is != null) { is.close(); } } } }
From source file:org.taverna.server.master.localworker.SecurityContextDelegateImpl.java
/** * Tests whether the given key-pair credential descriptor is valid. If it is * invalid, an exception will be thrown describing what the problem is. * /*from w w w. j a v a 2 s . co m*/ * @param keypairDescriptor * The descriptor to validate. * @throws InvalidCredentialException * If the descriptor is invalid * @throws KeyStoreException * If we don't understand the keystore type or the contents of * the keystore * @throws NoSuchAlgorithmException * If the keystore is of a known type but we can't comprehend * its security * @throws CertificateException * If the keystore does not include enough information about the * trust chain of the keypair * @throws UnrecoverableKeyException * If we can't get the key out of the keystore * @throws IOException * If we can't read the keystore for prosaic reasons (e.g., file * absent) */ protected void validateKeyCredential(Credential.KeyPair keypairDescriptor) throws InvalidCredentialException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException { if (keypairDescriptor.credentialName == null || keypairDescriptor.credentialName.trim().isEmpty()) throw new InvalidCredentialException("absent or empty credentialName"); InputStream contentsAsStream; if (keypairDescriptor.credentialBytes != null && keypairDescriptor.credentialBytes.length > 0) { contentsAsStream = new ByteArrayInputStream(keypairDescriptor.credentialBytes); keypairDescriptor.credentialFile = null; } else if (keypairDescriptor.credentialFile == null || keypairDescriptor.credentialFile.trim().isEmpty()) throw new InvalidCredentialException("absent or empty credentialFile"); else { contentsAsStream = contents(keypairDescriptor.credentialFile); keypairDescriptor.credentialBytes = new byte[0]; } if (keypairDescriptor.fileType == null || keypairDescriptor.fileType.trim().isEmpty()) keypairDescriptor.fileType = KeyStore.getDefaultType(); keypairDescriptor.fileType = keypairDescriptor.fileType.trim(); KeyStore ks = KeyStore.getInstance(keypairDescriptor.fileType); char[] password = keypairDescriptor.unlockPassword.toCharArray(); ks.load(contentsAsStream, password); try { keypairDescriptor.loadedKey = ks.getKey(keypairDescriptor.credentialName, password); } catch (UnrecoverableKeyException ignored) { keypairDescriptor.loadedKey = ks.getKey(keypairDescriptor.credentialName, new char[0]); } if (keypairDescriptor.loadedKey == null) throw new InvalidCredentialException("no such credential in key store"); keypairDescriptor.loadedTrustChain = ks.getCertificateChain(keypairDescriptor.credentialName); if (keypairDescriptor.loadedTrustChain == null || keypairDescriptor.loadedTrustChain.length == 0) throw new InvalidCredentialException("could not establish trust chain for credential"); }
From source file:com.prasanna.android.http.SecureHttpHelper.java
protected HttpClient createSecureHttpClient() { try {//from w ww . j ava 2 s . co m KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new SSLSocketFactoryX509(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme(SCHEME_HTTPS, sf, HTTPS_PORT)); schemeRegistry.register(new Scheme(SCHEME_HTTP, PlainSocketFactory.getSocketFactory(), HTTP_PORT)); return new DefaultHttpClient(new SingleClientConnManager(params, schemeRegistry), params); } catch (KeyManagementException e) { LogWrapper.e(TAG, e.getMessage()); } catch (UnrecoverableKeyException e) { LogWrapper.e(TAG, e.getMessage()); } catch (KeyStoreException e) { LogWrapper.e(TAG, e.getMessage()); } catch (NoSuchAlgorithmException e) { LogWrapper.e(TAG, e.getMessage()); } catch (CertificateException e) { LogWrapper.e(TAG, e.getMessage()); } catch (IOException e) { LogWrapper.e(TAG, e.getMessage()); } throw new ClientException(ClientErrorCode.HTTP_REQ_ERROR); }
From source file:com.appdynamics.monitors.mongo.MongoDBMonitor.java
private SSLSocketFactory getSocketFactoryFromPEM(String filePath) throws Exception { Security.addProvider(new BouncyCastleProvider()); PEMParser pemParser = new PEMParser(new FileReader(getConfigFilename(filePath))); pemParser.readObject();//from w w w . j a va2 s. c om PemObject pemObject = pemParser.readPemObject(); pemParser.close(); X509CertificateHolder holder = new X509CertificateHolder(pemObject.getContent()); X509Certificate bc = new JcaX509CertificateConverter().setProvider("BC").getCertificate(holder); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); keyStore.setCertificateEntry("ca", bc); TrustManager trustManager = TrustManagerUtils.getDefaultTrustManager(keyStore); SSLContext sslContext = SSLContextUtils.createSSLContext("TLS", null, trustManager); return sslContext.getSocketFactory(); }
From source file:org.wisdom.framework.vertx.ServerTest.java
/** * This methods checks HTTP, HTTPS and HTTPS with Mutual Authentication. *///from ww w .ja v a 2 s . c om @Test public void testCreationOfThreeServersFromConfiguration() throws InterruptedException, IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException { FakeConfiguration s1 = new FakeConfiguration(ImmutableMap.<String, Object>builder().put("port", 0) .put("ssl", false).put("authentication", false).build()); FakeConfiguration s2 = new FakeConfiguration(ImmutableMap.<String, Object>builder().put("port", 0) .put("ssl", true).put("authentication", false).build()); FakeConfiguration s3 = new FakeConfiguration(ImmutableMap.<String, Object>builder().put("port", 0) .put("ssl", true).put("authentication", true).build()); // Server HTTPS File root = new File(""); final File serverKeyStore = new File( root.getAbsolutePath() + "/src/test/resources/keystore/server/server.jks"); assertThat(serverKeyStore).isFile(); when(application.get("https.keyStore")).thenReturn(serverKeyStore.getAbsolutePath()); when(application.get("https.trustStore")) .thenReturn(new File(root.getAbsolutePath() + "/src/test/resources/keystore/server/server.jks") .getAbsolutePath()); when(application.getWithDefault("https.keyStoreType", "JKS")).thenReturn("JKS"); when(application.getWithDefault("https.trustStoreType", "JKS")).thenReturn("JKS"); when(application.getWithDefault("https.keyStorePassword", "")).thenReturn("wisdom"); when(application.getWithDefault("https.trustStorePassword", "")).thenReturn("wisdom"); when(application.getWithDefault("https.keyStoreAlgorithm", KeyManagerFactory.getDefaultAlgorithm())) .thenReturn(KeyManagerFactory.getDefaultAlgorithm()); when(application.getWithDefault("https.trustStoreAlgorithm", KeyManagerFactory.getDefaultAlgorithm())) .thenReturn(KeyManagerFactory.getDefaultAlgorithm()); when(application.getConfiguration("vertx.servers")) .thenReturn(new FakeConfiguration(ImmutableMap.<String, Object>of("s1", s1, "s2", s2, "s3", s3))); Controller controller = new DefaultController() { @SuppressWarnings("unused") public Result index() { return ok("Alright"); } }; Route route = new RouteBuilder().route(HttpMethod.GET).on("/").to(controller, "index"); when(router.getRouteFor(anyString(), anyString(), any(Request.class))).thenReturn(route); wisdom.start(); waitForStart(wisdom); waitForHttpsStart(wisdom); assertThat(wisdom.servers).hasSize(3); // Check rendering for (Server server : wisdom.servers) { String r; KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream("src/test/resources/keystore/client/client1.jks"); trustStore.load(instream, "wisdom".toCharArray()); // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom() .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()) .loadKeyMaterial(trustStore, "wisdom".toCharArray()).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1", "SSLv3" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); if (server.ssl()) { HttpGet httpget = new HttpGet("https://localhost:" + server.port()); final CloseableHttpResponse response = httpclient.execute(httpget); r = EntityUtils.toString(response.getEntity()); } else { r = org.apache.http.client.fluent.Request.Get("http://localhost:" + server.port()).execute() .returnContent().asString(); } assertThat(r).isEqualToIgnoringCase("Alright"); } }
From source file:com.allblacks.utils.web.HttpUtil.java
static HttpClient getNewHttpClient() { try {//from w w w. ja v a 2s . c om 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, 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); return new DefaultHttpClient(ccm, params); } catch (Exception e) { return new DefaultHttpClient(); } }
From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java
/** * To validate the current certificate and alias. * * @param alias Alias of the certificate. * @param certificate Bas64 endcoded certificated. * @return response code based on the validation *//*from w w w . ja va 2s.com*/ public ResponseCode validateCertificate(String alias, int tenantId, String certificate) { File trustStoreFile = new File(TRUST_STORE); ResponseCode responseCode = ResponseCode.SUCCESS; ByteArrayInputStream serverCert = null; try { localTrustStoreStream = new FileInputStream(trustStoreFile); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(localTrustStoreStream, TRUST_STORE_PASSWORD); if (StringUtils.isNotEmpty(alias) && trustStore.containsAlias(alias + "_" + tenantId)) { responseCode = ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE; } if (responseCode != ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE) { byte[] cert = (Base64.decodeBase64(certificate.getBytes(StandardCharsets.UTF_8))); serverCert = new ByteArrayInputStream(cert); if (serverCert.available() == 0) { responseCode = ResponseCode.CERTIFICATE_NOT_FOUND; } else { CertificateFactory cf = CertificateFactory.getInstance(CERTIFICATE_TYPE); while (serverCert.available() > 0) { Certificate generatedCertificate = cf.generateCertificate(serverCert); X509Certificate x509Certificate = (X509Certificate) generatedCertificate; if (x509Certificate.getNotAfter().getTime() <= System.currentTimeMillis()) { responseCode = ResponseCode.CERTIFICATE_EXPIRED; } } } } } catch (IOException e) { log.error("I/O Exception while trying to load trust store while trying to check whether alias " + alias + " exists", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (CertificateException e) { log.error("Certificate Exception while trying to load trust store while trying to check whether alias " + alias + " exists", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (NoSuchAlgorithmException e) { log.error("No Such Algorithm Exception while trying to load trust store while trying to check whether " + "alias " + alias + " exists", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (KeyStoreException e) { log.error("KeyStore Exception while trying to load trust store while trying to check whether alias " + alias + " exists", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } finally { closeStreams(serverCert); } return responseCode; }
From source file:org.roda.common.certification.ODFSignatureUtils.java
public static Path runDigitalSignatureSign(Path input, String ks, String alias, String password, String fileFormat) throws Exception { Security.addProvider(new BouncyCastleProvider()); Path output = Files.createTempFile("odfsigned", "." + fileFormat); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); InputStream storeStream = new FileInputStream(ks); keystore.load(storeStream, password.toCharArray()); X509Certificate certificate = (X509Certificate) keystore.getCertificate(keystore.aliases().nextElement()); Key key = keystore.getKey(alias, password.toCharArray()); IOUtils.closeQuietly(storeStream);/*www . j a v a 2 s . com*/ ByteArrayInputStream bais = createSignature(input.toString(), certificate, key); File file = output.toFile(); if (file != null) { byte[] buffer = new byte[2048]; int length = 0; FileOutputStream fos = new FileOutputStream(file); while ((length = bais.read(buffer)) >= 0) { fos.write(buffer, 0, length); } IOUtils.closeQuietly(fos); } return output; }