use of java.security.UnrecoverableKeyException 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.UnrecoverableKeyException in project opentheso by miledrousset.
the class HandleClient method deleteHandle.
/**
* Permet de supprimer l'identifiant Handle d'une resource
* @param pass
* @param pathKey
* @param pathCert
* @param urlHandle
* @param idHandle
* @return
*/
public boolean deleteHandle(String pass, String pathKey, String pathCert, String urlHandle, String idHandle) {
// exp : idHandle = (20.500.11942/LDx76olvIm)
String output;
String xmlRecord = "";
try {
KeyStore clientStore = KeyStore.getInstance("PKCS12");
// "motdepasse" = le mot de passe saisie pour la génération des certificats.
// clientStore.load(new FileInputStream("key.p12"), "motdepasse".toCharArray());
clientStore.load(this.getClass().getResourceAsStream(pathKey), pass.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(clientStore, pass.toCharArray());
KeyStore trustStore = KeyStore.getInstance("JKS");
// trustStore.load(new FileInputStream("cacerts2"), pass.toCharArray());
trustStore.load(this.getClass().getResourceAsStream(pathCert), pass.toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(trustStore);
SSLContext sslContext;
sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
// URL url = new URL("https://cchum-isi-handle01.in2p3.fr:8001/api/handles/20.500.11942/opentheso443");
URL url = new URL(urlHandle + idHandle);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(sslContext.getSocketFactory());
conn.setRequestMethod("DELETE");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "Handle clientCert=\"true\"");
conn.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
int status = conn.getResponseCode();
InputStream in = status >= 400 ? conn.getErrorStream() : conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while ((output = br.readLine()) != null) {
xmlRecord += output;
}
byte[] bytes = xmlRecord.getBytes();
xmlRecord = new String(bytes, Charset.forName("UTF-8"));
if (status == 200) {
message = "Suppression du Handle réussie";
}
if (status == 100) {
message = "Handle n'existe pas";
}
message = message + "\n" + xmlRecord;
message = message + "\n" + "status de la réponse : " + status;
return true;
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (KeyStoreException ex) {
Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (CertificateException ex) {
Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnrecoverableKeyException ex) {
Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (KeyManagementException ex) {
Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (MalformedURLException ex) {
Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
use of java.security.UnrecoverableKeyException in project opentheso by miledrousset.
the class HandleClient method updateHandle.
/**
* Permet de mettre à jour l'URL et les données d'une resource Handle
* cette fonction donne la même action que le putHandle
* @param pass
* @param pathKey
* @param pathCert
* @param urlHandle
* @param idHandle
* @param jsonData
* @return
*/
public boolean updateHandle(String pass, String pathKey, String pathCert, String urlHandle, String idHandle, String jsonData) {
String output;
String xmlRecord = "";
try {
KeyStore clientStore = KeyStore.getInstance("PKCS12");
// "motdepasse" = le mot de passe saisie pour la génération des certificats.
// clientStore.load(new FileInputStream("key.p12"), "motdepasse".toCharArray());
clientStore.load(this.getClass().getResourceAsStream(pathKey), pass.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(clientStore, pass.toCharArray());
KeyStore trustStore = KeyStore.getInstance("JKS");
// trustStore.load(new FileInputStream("cacerts2"), pass.toCharArray());
trustStore.load(this.getClass().getResourceAsStream(pathCert), pass.toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(trustStore);
SSLContext sslContext;
sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
// URL url = new URL("https://cchum-isi-handle01.in2p3.fr:8001/api/handles/20.500.11942/opentheso443");
URL url = new URL(urlHandle + idHandle);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(sslContext.getSocketFactory());
conn.setRequestMethod("PUT");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "Handle clientCert=\"true\"");
conn.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
OutputStreamWriter out = new OutputStreamWriter(os);
out.write(jsonData);
out.flush();
int status = conn.getResponseCode();
InputStream in = status >= 400 ? conn.getErrorStream() : conn.getInputStream();
// status = 201 = création réussie
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while ((output = br.readLine()) != null) {
xmlRecord += output;
}
byte[] bytes = xmlRecord.getBytes();
xmlRecord = new String(bytes, Charset.forName("UTF-8"));
os.close();
conn.disconnect();
if (status == 200) {
message = "Mise à jour du Handle réussie";
}
if (status == 100) {
message = "Handle n'existe pas";
}
message = message + "\n" + xmlRecord;
message = message + "\n" + "status de la réponse : " + status;
return true;
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (KeyStoreException ex) {
Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (CertificateException ex) {
Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnrecoverableKeyException ex) {
Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (KeyManagementException ex) {
Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (MalformedURLException ex) {
Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
use of java.security.UnrecoverableKeyException in project Payara by payara.
the class RelativePathResolver method getRealPasswordFromAlias.
/**
* Returns the actual password from the domain-wide safe password store,
* if the given password is aliased. An aliased String is of the form
* ${ALIAS=aliasname} where the actual password is stored in given alias name.
* Following are the returned values:
* <ul>
* <li> Returns a null if given String is null. </li>
* <li> Retuns the given String if it is not in the alias form. </li>
* <li> Returns the real password from store if the given String is
* of the alias form and the alias has been created by the
* administrator. If the alias is not defined in the store,
* an IllegalArgumentException is thrown with appropriate
* message. </li>
* </ul>
* @param at is the aliased token of the form "${ALIAS=string}"
* @return a String representing the actual password
* @throws IllegalArgumentException if the alias is not defined
* @throws KeyStoreException CertificateException IOException NoSuchAlgorithmException
* UnrecoverableKeyException if there is an error is opening or
* processing the password store
*/
public static String getRealPasswordFromAlias(final String at) throws KeyStoreException, CertificateException, IOException, NoSuchAlgorithmException, UnrecoverableKeyException {
try {
if (at == null || RelativePathResolver.getAlias(at) == null) {
return (at);
}
} catch (final Exception e) {
// underlying code is unsafe!
return (at);
}
final String an = RelativePathResolver.getAlias(at);
final boolean exists = getDomainPasswordAliasStore().containsKey(an);
if (!exists) {
final StringManager lsm = StringManager.getManager(RelativePathResolver.class);
final String msg = lsm.getString("no_such_alias", an, at);
throw new IllegalArgumentException(msg);
}
final String real = new String(getDomainPasswordAliasStore().get(an));
return (real);
}
use of java.security.UnrecoverableKeyException in project ORCID-Source by ORCID.
the class OrcidJerseyT2ClientConfig method createSslContext.
private SSLContext createSslContext() {
try {
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(keyStore, keyStorePassword.toCharArray());
KeyManager[] keyManagers = kmf.getKeyManagers();
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
// Use the trustStore if present, otherwise default to keyStore.
if (trustStore != null) {
tmf.init(trustStore);
} else {
tmf.init(keyStore);
}
TrustManager[] trustManagers = tmf.getTrustManagers();
SSLContext ssl = SSLContext.getInstance("TLS");
ssl.init(keyManagers, trustManagers, new SecureRandom());
return ssl;
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (KeyStoreException e) {
throw new RuntimeException(e);
} catch (UnrecoverableKeyException e) {
throw new RuntimeException(e);
} catch (KeyManagementException e) {
throw new RuntimeException(e);
}
}
Aggregations