use of java.security.KeyManagementException in project rabbitmq-java-client by rabbitmq.
the class VerifiedConnection method openConnection.
public void openConnection() throws IOException, TimeoutException {
try {
String keystorePath = System.getProperty("test-keystore.ca");
assertNotNull(keystorePath);
String keystorePasswd = System.getProperty("test-keystore.password");
assertNotNull(keystorePasswd);
char[] keystorePassword = keystorePasswd.toCharArray();
KeyStore tks = KeyStore.getInstance("JKS");
tks.load(new FileInputStream(keystorePath), keystorePassword);
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(tks);
String p12Path = System.getProperty("test-client-cert.path");
assertNotNull(p12Path);
String p12Passwd = System.getProperty("test-client-cert.password");
assertNotNull(p12Passwd);
KeyStore ks = KeyStore.getInstance("PKCS12");
char[] p12Password = p12Passwd.toCharArray();
ks.load(new FileInputStream(p12Path), p12Password);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, p12Password);
SSLContext c = getSSLContext();
c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
connectionFactory = TestUtils.connectionFactory();
connectionFactory.useSslProtocol(c);
} catch (NoSuchAlgorithmException ex) {
throw new IOException(ex.toString());
} catch (KeyManagementException ex) {
throw new IOException(ex.toString());
} catch (KeyStoreException ex) {
throw new IOException(ex.toString());
} catch (CertificateException ex) {
throw new IOException(ex.toString());
} catch (UnrecoverableKeyException ex) {
throw new IOException(ex.toString());
}
int attempt = 0;
while (attempt < 3) {
try {
connection = connectionFactory.newConnection();
break;
} catch (Exception e) {
LoggerFactory.getLogger(getClass()).warn("Error when opening TLS connection");
attempt++;
}
}
if (connection == null) {
fail("Couldn't open TLS connection after 3 attemps");
}
}
use of java.security.KeyManagementException in project ignite by apache.
the class UriDeploymentHttpScanner method createUriContext.
/**
* Create context for the given URI.
*
* @param uri URI.
* @param scanCtx Scanner context.
* @return URI context.
*/
private URIContext createUriContext(URI uri, final UriDeploymentScannerContext scanCtx) {
assert "http".equals(uri.getScheme()) || "https".equals(uri.getScheme());
URL scanDir;
try {
scanDir = new URL(uri.getScheme(), uri.getHost(), uri.getPort(), uri.getPath());
} catch (MalformedURLException e) {
throw new IgniteSpiException("Wrong value for scanned HTTP directory with URI: " + uri, e);
}
SSLSocketFactory sockFactory = null;
try {
if ("https".equals(uri.getScheme())) {
// Set up socket factory to do authentication.
SSLContext ctx = SSLContext.getInstance(PROTOCOL);
ctx.init(null, getTrustManagers(scanCtx), null);
sockFactory = ctx.getSocketFactory();
}
} catch (NoSuchAlgorithmException e) {
throw new IgniteSpiException("Failed to initialize SSL context. URI: " + uri, e);
} catch (KeyManagementException e) {
throw new IgniteSpiException("Failed to initialize SSL context. URI:" + uri, e);
}
return new URIContext(scanDir, sockFactory);
}
use of java.security.KeyManagementException in project aware-client by denzilferreira.
the class DownloadPluginService method onHandleIntent.
@Override
protected void onHandleIntent(Intent intent) {
final NotificationManager notManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String package_name = intent.getStringExtra("package_name");
boolean is_update = intent.getBooleanExtra("is_update", false);
String study_url = Aware.getSetting(getApplicationContext(), Aware_Preferences.WEBSERVICE_SERVER);
if (intent.hasExtra("study_url"))
study_url = intent.getStringExtra("study_url");
if (Aware.DEBUG)
Log.d(Aware.TAG, "Trying to download: " + package_name + " using server: " + study_url);
String study_host = study_url.substring(0, study_url.indexOf("/index.php"));
String protocol = study_url.substring(0, study_url.indexOf(":"));
String response;
if (protocol.equals("https")) {
try {
response = new Https(SSLManager.getHTTPS(getApplicationContext(), study_url)).dataGET(study_url.substring(0, study_url.indexOf("/index.php")) + "/index.php/plugins/get_plugin/" + package_name, true);
} catch (FileNotFoundException e) {
response = null;
}
} else {
response = new Http().dataGET(study_url.substring(0, study_url.indexOf("/index.php")) + "/index.php/plugins/get_plugin/" + package_name, true);
}
if (response != null) {
try {
if (response.trim().equalsIgnoreCase("[]")) {
Toast.makeText(getApplicationContext(), "Please install this plugin", Toast.LENGTH_LONG).show();
Intent playInstaller = new Intent(Intent.ACTION_VIEW);
playInstaller.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
playInstaller.setData(Uri.parse("market://details?id=" + package_name));
startActivity(playInstaller);
return;
}
JSONObject json_package = new JSONObject(response);
// Create the folder where all the plugins will be stored on external storage
File folders = new File(Environment.getExternalStoragePublicDirectory("AWARE/plugins").toString());
folders.mkdirs();
String package_url = study_host + json_package.getString("package_path") + json_package.getString("package_name");
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext(), Aware.AWARE_NOTIFICATION_ID);
mBuilder.setSmallIcon(R.drawable.ic_action_aware_plugins);
mBuilder.setContentTitle("AWARE Plugin");
mBuilder.setContentText(((is_update) ? "Updating " : "Downloading ") + json_package.getString("title"));
mBuilder.setProgress(0, 0, true);
mBuilder.setAutoCancel(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
mBuilder.setChannelId(Aware.AWARE_NOTIFICATION_ID);
final int notID = new Random(System.currentTimeMillis()).nextInt();
notManager.notify(notID, mBuilder.build());
if (protocol.equals("https")) {
// Load SSL public certificate so we can talk with server
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream caInput = SSLManager.getHTTPS(getApplicationContext(), study_url);
Certificate ca = cf.generateCertificate(caInput);
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
// initialize as empty keystore
keyStore.load(null, null);
// add our certificate to keystore
keyStore.setCertificateEntry("ca", ca);
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
// add our keystore to the trusted keystores
trustManagerFactory.init(keyStore);
// Initialize a SSL connection context
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
// Fix for known-bug on <= JellyBean (4.x)
System.setProperty("http.keepAlive", "false");
Ion.getDefault(getApplicationContext()).getConscryptMiddleware().enable(false);
Ion.getDefault(getApplicationContext()).getHttpClient().getSSLSocketMiddleware().setTrustManagers(trustManagerFactory.getTrustManagers());
Ion.getDefault(getApplicationContext()).getHttpClient().getSSLSocketMiddleware().setSSLContext(sslContext);
}
Ion.getDefault(getApplicationContext()).getConscryptMiddleware().enable(false);
Ion.with(getApplicationContext()).load(package_url).noCache().write(new File(Environment.getExternalStoragePublicDirectory("AWARE/plugins/" + json_package.getString("package_name")).toString())).setCallback(new FutureCallback<File>() {
@Override
public void onCompleted(Exception e, File result) {
if (result != null) {
notManager.cancel(notID);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Intent promptInstall = new Intent(Intent.ACTION_VIEW);
promptInstall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
promptInstall.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
promptInstall.setDataAndType(FileProvider.getUriForFile(getApplicationContext(), getPackageName() + ".provider.storage", result), "application/vnd.android.package-archive");
startActivity(promptInstall);
} else {
Intent promptInstall = new Intent(Intent.ACTION_VIEW);
promptInstall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
promptInstall.setDataAndType(Uri.fromFile(result), "application/vnd.android.package-archive");
startActivity(promptInstall);
}
}
}
});
} catch (JSONException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
// We don't have it on our server, let's try the Play Store
downloadToast = Toast.makeText(getApplicationContext(), "Please install this plugin", Toast.LENGTH_SHORT);
downloadToast.show();
Intent playInstaller = new Intent(Intent.ACTION_VIEW);
playInstaller.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
playInstaller.setData(Uri.parse("market://details?id=" + package_name));
startActivity(playInstaller);
}
}
use of java.security.KeyManagementException in project ignite by apache.
the class JdbcThinSSLUtil method getSSLSocketFactory.
/**
* @param connProps Connection properties.
* @return SSL socket factory.
* @throws SQLException On error.
*/
private static SSLSocketFactory getSSLSocketFactory(ConnectionProperties connProps) throws SQLException {
String sslFactory = connProps.getSslFactory();
String cliCertKeyStoreUrl = connProps.getSslClientCertificateKeyStoreUrl();
String cliCertKeyStorePwd = connProps.getSslClientCertificateKeyStorePassword();
String cliCertKeyStoreType = connProps.getSslClientCertificateKeyStoreType();
String trustCertKeyStoreUrl = connProps.getSslTrustCertificateKeyStoreUrl();
String trustCertKeyStorePwd = connProps.getSslTrustCertificateKeyStorePassword();
String trustCertKeyStoreType = connProps.getSslTrustCertificateKeyStoreType();
String sslProtocol = connProps.getSslProtocol();
String keyAlgorithm = connProps.getSslKeyAlgorithm();
if (!F.isEmpty(sslFactory)) {
try {
Class<Factory<SSLSocketFactory>> cls = (Class<Factory<SSLSocketFactory>>) JdbcThinSSLUtil.class.getClassLoader().loadClass(sslFactory);
Factory<SSLSocketFactory> f = cls.newInstance();
return f.create();
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
throw new SQLException("Could not fount SSL factory class: " + sslFactory, SqlStateCode.CLIENT_CONNECTION_FAILED, e);
}
}
if (cliCertKeyStoreUrl == null && cliCertKeyStorePwd == null && cliCertKeyStoreType == null && trustCertKeyStoreUrl == null && trustCertKeyStorePwd == null && trustCertKeyStoreType == null && sslProtocol == null) {
try {
return SSLContext.getDefault().getSocketFactory();
} catch (NoSuchAlgorithmException e) {
throw new SQLException("Could not create default SSL context", SqlStateCode.CLIENT_CONNECTION_FAILED, e);
}
}
if (cliCertKeyStoreUrl == null)
cliCertKeyStoreUrl = System.getProperty("javax.net.ssl.keyStore");
if (cliCertKeyStorePwd == null)
cliCertKeyStorePwd = System.getProperty("javax.net.ssl.keyStorePassword");
if (cliCertKeyStoreType == null)
cliCertKeyStoreType = System.getProperty("javax.net.ssl.keyStoreType", "JKS");
if (trustCertKeyStoreUrl == null)
trustCertKeyStoreUrl = System.getProperty("javax.net.ssl.trustStore");
if (trustCertKeyStorePwd == null)
trustCertKeyStorePwd = System.getProperty("javax.net.ssl.trustStorePassword");
if (trustCertKeyStoreType == null)
trustCertKeyStoreType = System.getProperty("javax.net.ssl.trustStoreType", "JKS");
if (sslProtocol == null)
sslProtocol = "TLS";
if (!F.isEmpty(cliCertKeyStoreUrl))
cliCertKeyStoreUrl = checkAndConvertUrl(cliCertKeyStoreUrl);
if (!F.isEmpty(trustCertKeyStoreUrl))
trustCertKeyStoreUrl = checkAndConvertUrl(trustCertKeyStoreUrl);
TrustManagerFactory tmf;
KeyManagerFactory kmf;
KeyManager[] kms = null;
try {
tmf = TrustManagerFactory.getInstance(keyAlgorithm);
kmf = KeyManagerFactory.getInstance(keyAlgorithm);
} catch (NoSuchAlgorithmException e) {
throw new SQLException("Default algorithm definitions for TrustManager and/or KeyManager are invalid." + " Check java security properties file.", SqlStateCode.CLIENT_CONNECTION_FAILED, e);
}
InputStream ksInputStream = null;
try {
if (!F.isEmpty(cliCertKeyStoreUrl) && !F.isEmpty(cliCertKeyStoreType)) {
KeyStore clientKeyStore = KeyStore.getInstance(cliCertKeyStoreType);
URL ksURL = new URL(cliCertKeyStoreUrl);
char[] password = (cliCertKeyStorePwd == null) ? new char[0] : cliCertKeyStorePwd.toCharArray();
ksInputStream = ksURL.openStream();
clientKeyStore.load(ksInputStream, password);
kmf.init(clientKeyStore, password);
kms = kmf.getKeyManagers();
}
} catch (UnrecoverableKeyException e) {
throw new SQLException("Could not recover keys from client keystore.", SqlStateCode.CLIENT_CONNECTION_FAILED, e);
} catch (NoSuchAlgorithmException e) {
throw new SQLException("Unsupported keystore algorithm.", SqlStateCode.CLIENT_CONNECTION_FAILED, e);
} catch (KeyStoreException e) {
throw new SQLException("Could not create client KeyStore instance.", SqlStateCode.CLIENT_CONNECTION_FAILED, e);
} catch (CertificateException e) {
throw new SQLException("Could not load client key store. [storeType=" + cliCertKeyStoreType + ", cliStoreUrl=" + cliCertKeyStoreUrl + ']', SqlStateCode.CLIENT_CONNECTION_FAILED, e);
} catch (MalformedURLException e) {
throw new SQLException("Invalid client key store URL. [url=" + cliCertKeyStoreUrl + ']', SqlStateCode.CLIENT_CONNECTION_FAILED, e);
} catch (IOException e) {
throw new SQLException("Could not open client key store.[url=" + cliCertKeyStoreUrl + ']', SqlStateCode.CLIENT_CONNECTION_FAILED, e);
} finally {
if (ksInputStream != null) {
try {
ksInputStream.close();
} catch (IOException e) {
// can't close input stream, but keystore can be properly initialized
// so we shouldn't throw this exception
}
}
}
InputStream tsInputStream = null;
List<TrustManager> tms;
if (connProps.isSslTrustAll())
tms = Collections.<TrustManager>singletonList(TRUST_ALL_MANAGER);
else {
tms = new ArrayList<>();
try {
KeyStore trustKeyStore = null;
if (!F.isEmpty(trustCertKeyStoreUrl) && !F.isEmpty(trustCertKeyStoreType)) {
char[] trustStorePassword = (trustCertKeyStorePwd == null) ? new char[0] : trustCertKeyStorePwd.toCharArray();
tsInputStream = new URL(trustCertKeyStoreUrl).openStream();
trustKeyStore = KeyStore.getInstance(trustCertKeyStoreType);
trustKeyStore.load(tsInputStream, trustStorePassword);
}
tmf.init(trustKeyStore);
TrustManager[] origTms = tmf.getTrustManagers();
Collections.addAll(tms, origTms);
} catch (NoSuchAlgorithmException e) {
throw new SQLException("Unsupported keystore algorithm.", SqlStateCode.CLIENT_CONNECTION_FAILED, e);
} catch (KeyStoreException e) {
throw new SQLException("Could not create trust KeyStore instance.", SqlStateCode.CLIENT_CONNECTION_FAILED, e);
} catch (CertificateException e) {
throw new SQLException("Could not load trusted key store. [storeType=" + trustCertKeyStoreType + ", cliStoreUrl=" + trustCertKeyStoreUrl + ']', SqlStateCode.CLIENT_CONNECTION_FAILED, e);
} catch (MalformedURLException e) {
throw new SQLException("Invalid trusted key store URL. [url=" + trustCertKeyStoreUrl + ']', SqlStateCode.CLIENT_CONNECTION_FAILED, e);
} catch (IOException e) {
throw new SQLException("Could not open trusted key store. [url=" + cliCertKeyStoreUrl + ']', SqlStateCode.CLIENT_CONNECTION_FAILED, e);
} finally {
if (tsInputStream != null) {
try {
tsInputStream.close();
} catch (IOException e) {
// can't close input stream, but keystore can be properly initialized
// so we shouldn't throw this exception
}
}
}
}
assert tms.size() != 0;
try {
SSLContext sslContext = SSLContext.getInstance(sslProtocol);
sslContext.init(kms, tms.toArray(new TrustManager[tms.size()]), null);
return sslContext.getSocketFactory();
} catch (NoSuchAlgorithmException e) {
throw new SQLException(sslProtocol + " is not a valid SSL protocol.", SqlStateCode.CLIENT_CONNECTION_FAILED, e);
} catch (KeyManagementException e) {
throw new SQLException("Cannot init SSL context.", SqlStateCode.CLIENT_CONNECTION_FAILED, e);
}
}
use of java.security.KeyManagementException in project ignite by apache.
the class IgniteUtils method downloadUrl.
/**
* Downloads resource by URL.
*
* @param url URL to download.
* @param file File where downloaded resource should be stored.
* @return File where downloaded resource should be stored.
* @throws IOException If error occurred.
*/
public static File downloadUrl(URL url, File file) throws IOException {
assert url != null;
assert file != null;
InputStream in = null;
OutputStream out = null;
try {
URLConnection conn = url.openConnection();
if (conn instanceof HttpsURLConnection) {
HttpsURLConnection https = (HttpsURLConnection) conn;
https.setHostnameVerifier(new DeploymentHostnameVerifier());
SSLContext ctx = SSLContext.getInstance(HTTPS_PROTOCOL);
ctx.init(null, getTrustManagers(), null);
// Initialize socket factory.
https.setSSLSocketFactory(ctx.getSocketFactory());
}
in = conn.getInputStream();
if (in == null)
throw new IOException("Failed to open connection: " + url.toString());
out = new BufferedOutputStream(new FileOutputStream(file));
copy(in, out);
} catch (NoSuchAlgorithmException | KeyManagementException e) {
throw new IOException("Failed to open HTTPs connection [url=" + url.toString() + ", msg=" + e + ']', e);
} finally {
close(in, null);
close(out, null);
}
return file;
}
Aggregations