use of java.security.UnrecoverableKeyException in project jersey by jersey.
the class SslConfigurator method createSSLContext.
/**
* Create new SSL context instance using the current SSL context configuration.
*
* @return newly configured SSL context instance.
*/
public SSLContext createSSLContext() {
TrustManagerFactory trustManagerFactory = null;
KeyManagerFactory keyManagerFactory = null;
KeyStore _keyStore = keyStore;
if (_keyStore == null && (keyStoreBytes != null || keyStoreFile != null)) {
try {
if (keyStoreProvider != null) {
_keyStore = KeyStore.getInstance(keyStoreType != null ? keyStoreType : KeyStore.getDefaultType(), keyStoreProvider);
} else {
_keyStore = KeyStore.getInstance(keyStoreType != null ? keyStoreType : KeyStore.getDefaultType());
}
InputStream keyStoreInputStream = null;
try {
if (keyStoreBytes != null) {
keyStoreInputStream = new ByteArrayInputStream(keyStoreBytes);
} else if (!keyStoreFile.equals("NONE")) {
keyStoreInputStream = new FileInputStream(keyStoreFile);
}
_keyStore.load(keyStoreInputStream, keyStorePass);
} finally {
try {
if (keyStoreInputStream != null) {
keyStoreInputStream.close();
}
} catch (IOException ignored) {
}
}
} catch (KeyStoreException e) {
throw new IllegalStateException(LocalizationMessages.SSL_KS_IMPL_NOT_FOUND(), e);
} catch (CertificateException e) {
throw new IllegalStateException(LocalizationMessages.SSL_KS_CERT_LOAD_ERROR(), e);
} catch (FileNotFoundException e) {
throw new IllegalStateException(LocalizationMessages.SSL_KS_FILE_NOT_FOUND(keyStoreFile), e);
} catch (IOException e) {
throw new IllegalStateException(LocalizationMessages.SSL_KS_LOAD_ERROR(keyStoreFile), e);
} catch (NoSuchProviderException e) {
throw new IllegalStateException(LocalizationMessages.SSL_KS_PROVIDERS_NOT_REGISTERED(), e);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(LocalizationMessages.SSL_KS_INTEGRITY_ALGORITHM_NOT_FOUND(), e);
}
}
if (_keyStore != null) {
String kmfAlgorithm = keyManagerFactoryAlgorithm;
if (kmfAlgorithm == null) {
kmfAlgorithm = AccessController.doPrivileged(PropertiesHelper.getSystemProperty(KEY_MANAGER_FACTORY_ALGORITHM, KeyManagerFactory.getDefaultAlgorithm()));
}
try {
if (keyManagerFactoryProvider != null) {
keyManagerFactory = KeyManagerFactory.getInstance(kmfAlgorithm, keyManagerFactoryProvider);
} else {
keyManagerFactory = KeyManagerFactory.getInstance(kmfAlgorithm);
}
final char[] password = keyPass != null ? keyPass : keyStorePass;
if (password != null) {
keyManagerFactory.init(_keyStore, password);
} else {
String ksName = keyStoreProvider != null ? LocalizationMessages.SSL_KMF_NO_PASSWORD_FOR_PROVIDER_BASED_KS() : keyStoreBytes != null ? LocalizationMessages.SSL_KMF_NO_PASSWORD_FOR_BYTE_BASED_KS() : keyStoreFile;
LOGGER.config(LocalizationMessages.SSL_KMF_NO_PASSWORD_SET(ksName));
keyManagerFactory = null;
}
} catch (KeyStoreException e) {
throw new IllegalStateException(LocalizationMessages.SSL_KMF_INIT_FAILED(), e);
} catch (UnrecoverableKeyException e) {
throw new IllegalStateException(LocalizationMessages.SSL_KMF_UNRECOVERABLE_KEY(), e);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(LocalizationMessages.SSL_KMF_ALGORITHM_NOT_SUPPORTED(), e);
} catch (NoSuchProviderException e) {
throw new IllegalStateException(LocalizationMessages.SSL_KMF_PROVIDER_NOT_REGISTERED(), e);
}
}
KeyStore _trustStore = trustStore;
if (_trustStore == null && (trustStoreBytes != null || trustStoreFile != null)) {
try {
if (trustStoreProvider != null) {
_trustStore = KeyStore.getInstance(trustStoreType != null ? trustStoreType : KeyStore.getDefaultType(), trustStoreProvider);
} else {
_trustStore = KeyStore.getInstance(trustStoreType != null ? trustStoreType : KeyStore.getDefaultType());
}
InputStream trustStoreInputStream = null;
try {
if (trustStoreBytes != null) {
trustStoreInputStream = new ByteArrayInputStream(trustStoreBytes);
} else if (!trustStoreFile.equals("NONE")) {
trustStoreInputStream = new FileInputStream(trustStoreFile);
}
_trustStore.load(trustStoreInputStream, trustStorePass);
} finally {
try {
if (trustStoreInputStream != null) {
trustStoreInputStream.close();
}
} catch (IOException ignored) {
}
}
} catch (KeyStoreException e) {
throw new IllegalStateException(LocalizationMessages.SSL_TS_IMPL_NOT_FOUND(), e);
} catch (CertificateException e) {
throw new IllegalStateException(LocalizationMessages.SSL_TS_CERT_LOAD_ERROR(), e);
} catch (FileNotFoundException e) {
throw new IllegalStateException(LocalizationMessages.SSL_TS_FILE_NOT_FOUND(trustStoreFile), e);
} catch (IOException e) {
throw new IllegalStateException(LocalizationMessages.SSL_TS_LOAD_ERROR(trustStoreFile), e);
} catch (NoSuchProviderException e) {
throw new IllegalStateException(LocalizationMessages.SSL_TS_PROVIDERS_NOT_REGISTERED(), e);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(LocalizationMessages.SSL_TS_INTEGRITY_ALGORITHM_NOT_FOUND(), e);
}
}
if (_trustStore != null) {
String tmfAlgorithm = trustManagerFactoryAlgorithm;
if (tmfAlgorithm == null) {
tmfAlgorithm = AccessController.doPrivileged(PropertiesHelper.getSystemProperty(TRUST_MANAGER_FACTORY_ALGORITHM, TrustManagerFactory.getDefaultAlgorithm()));
}
try {
if (trustManagerFactoryProvider != null) {
trustManagerFactory = TrustManagerFactory.getInstance(tmfAlgorithm, trustManagerFactoryProvider);
} else {
trustManagerFactory = TrustManagerFactory.getInstance(tmfAlgorithm);
}
trustManagerFactory.init(_trustStore);
} catch (KeyStoreException e) {
throw new IllegalStateException(LocalizationMessages.SSL_TMF_INIT_FAILED(), e);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(LocalizationMessages.SSL_TMF_ALGORITHM_NOT_SUPPORTED(), e);
} catch (NoSuchProviderException e) {
throw new IllegalStateException(LocalizationMessages.SSL_TMF_PROVIDER_NOT_REGISTERED(), e);
}
}
try {
String secProtocol = "TLS";
if (securityProtocol != null) {
secProtocol = securityProtocol;
}
final SSLContext sslContext = SSLContext.getInstance(secProtocol);
sslContext.init(keyManagerFactory != null ? keyManagerFactory.getKeyManagers() : null, trustManagerFactory != null ? trustManagerFactory.getTrustManagers() : null, null);
return sslContext;
} catch (KeyManagementException e) {
throw new IllegalStateException(LocalizationMessages.SSL_CTX_INIT_FAILED(), e);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(LocalizationMessages.SSL_CTX_ALGORITHM_NOT_SUPPORTED(), e);
}
}
use of java.security.UnrecoverableKeyException in project buck by facebook.
the class ApkBuilderStep method execute.
@Override
public StepExecutionResult execute(ExecutionContext context) throws IOException {
PrintStream output = null;
if (context.getVerbosity().shouldUseVerbosityFlagIfAvailable()) {
output = context.getStdOut();
}
try {
PrivateKeyAndCertificate privateKeyAndCertificate = createKeystoreProperties();
ApkBuilder builder = new ApkBuilder(filesystem.getPathForRelativePath(pathToOutputApkFile).toFile(), filesystem.getPathForRelativePath(resourceApk).toFile(), filesystem.getPathForRelativePath(dexFile).toFile(), privateKeyAndCertificate.privateKey, privateKeyAndCertificate.certificate, output);
builder.setDebugMode(debugMode);
for (Path nativeLibraryDirectory : nativeLibraryDirectories) {
builder.addNativeLibraries(filesystem.getPathForRelativePath(nativeLibraryDirectory).toFile());
}
for (Path assetDirectory : assetDirectories) {
builder.addSourceFolder(filesystem.getPathForRelativePath(assetDirectory).toFile());
}
for (Path zipFile : zipFiles) {
// TODO(natthu): Skipping silently is bad. These should really be assertions.
if (filesystem.exists(zipFile) && filesystem.isFile(zipFile)) {
builder.addZipFile(filesystem.getPathForRelativePath(zipFile).toFile());
}
}
for (Path jarFileThatMayContainResources : jarFilesThatMayContainResources) {
Path jarFile = filesystem.getPathForRelativePath(jarFileThatMayContainResources);
builder.addResourcesFromJar(jarFile.toFile());
}
// Build the APK
builder.sealApk();
} catch (ApkCreationException | IOException | KeyStoreException | NoSuchAlgorithmException | SealedApkException | UnrecoverableKeyException e) {
context.logError(e, "Error when creating APK at: %s.", pathToOutputApkFile);
Throwables.throwIfInstanceOf(e, IOException.class);
return StepExecutionResult.ERROR;
} catch (DuplicateFileException e) {
throw new HumanReadableException(String.format("Found duplicate file for APK: %1$s\nOrigin 1: %2$s\nOrigin 2: %3$s", e.getArchivePath(), e.getFile1(), e.getFile2()));
}
return StepExecutionResult.SUCCESS;
}
use of java.security.UnrecoverableKeyException in project cassandra by apache.
the class CqlConfigHelper method getSSLOptions.
public static Optional<SSLOptions> getSSLOptions(Configuration conf) {
Optional<String> truststorePath = getInputNativeSSLTruststorePath(conf);
if (truststorePath.isPresent()) {
Optional<String> keystorePath = getInputNativeSSLKeystorePath(conf);
Optional<String> truststorePassword = getInputNativeSSLTruststorePassword(conf);
Optional<String> keystorePassword = getInputNativeSSLKeystorePassword(conf);
Optional<String> cipherSuites = getInputNativeSSLCipherSuites(conf);
SSLContext context;
try {
context = getSSLContext(truststorePath, truststorePassword, keystorePath, keystorePassword);
} catch (UnrecoverableKeyException | KeyManagementException | NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException e) {
throw new RuntimeException(e);
}
String[] css = null;
if (cipherSuites.isPresent())
css = cipherSuites.get().split(",");
return Optional.of(JdkSSLOptions.builder().withSSLContext(context).withCipherSuites(css).build());
}
return Optional.absent();
}
use of java.security.UnrecoverableKeyException in project okhttputils by hongyangAndroid.
the class HttpsUtils method prepareKeyManager.
private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) {
try {
if (bksFile == null || password == null)
return null;
KeyStore clientKeyStore = KeyStore.getInstance("BKS");
clientKeyStore.load(bksFile, password.toCharArray());
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(clientKeyStore, password.toCharArray());
return keyManagerFactory.getKeyManagers();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
use of java.security.UnrecoverableKeyException in project Smack by igniterealtime.
the class XMPPTCPConnection method proceedTLSReceived.
/**
* The server has indicated that TLS negotiation can start. We now need to secure the
* existing plain connection and perform a handshake. This method won't return until the
* connection has finished the handshake or an error occurred while securing the connection.
* @throws IOException
* @throws CertificateException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws KeyStoreException
* @throws UnrecoverableKeyException
* @throws KeyManagementException
* @throws SmackException
* @throws Exception if an exception occurs.
*/
@SuppressWarnings("LiteralClassName")
private void proceedTLSReceived() throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException, NoSuchProviderException, UnrecoverableKeyException, KeyManagementException, SmackException {
SSLContext context = this.config.getCustomSSLContext();
KeyStore ks = null;
KeyManager[] kms = null;
PasswordCallback pcb = null;
SmackDaneVerifier daneVerifier = null;
if (config.getDnssecMode() == DnssecMode.needsDnssecAndDane) {
SmackDaneProvider daneProvider = DNSUtil.getDaneProvider();
if (daneProvider == null) {
throw new UnsupportedOperationException("DANE enabled but no SmackDaneProvider configured");
}
daneVerifier = daneProvider.newInstance();
if (daneVerifier == null) {
throw new IllegalStateException("DANE requested but DANE provider did not return a DANE verifier");
}
}
if (context == null) {
final String keyStoreType = config.getKeystoreType();
final CallbackHandler callbackHandler = config.getCallbackHandler();
final String keystorePath = config.getKeystorePath();
if ("PKCS11".equals(keyStoreType)) {
try {
Constructor<?> c = Class.forName("sun.security.pkcs11.SunPKCS11").getConstructor(InputStream.class);
String pkcs11Config = "name = SmartCard\nlibrary = " + config.getPKCS11Library();
ByteArrayInputStream config = new ByteArrayInputStream(pkcs11Config.getBytes(StringUtils.UTF8));
Provider p = (Provider) c.newInstance(config);
Security.addProvider(p);
ks = KeyStore.getInstance("PKCS11", p);
pcb = new PasswordCallback("PKCS11 Password: ", false);
callbackHandler.handle(new Callback[] { pcb });
ks.load(null, pcb.getPassword());
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Exception", e);
ks = null;
}
} else if ("Apple".equals(keyStoreType)) {
ks = KeyStore.getInstance("KeychainStore", "Apple");
ks.load(null, null);
//pcb = new PasswordCallback("Apple Keychain",false);
//pcb.setPassword(null);
} else if (keyStoreType != null) {
ks = KeyStore.getInstance(keyStoreType);
if (callbackHandler != null && StringUtils.isNotEmpty(keystorePath)) {
try {
pcb = new PasswordCallback("Keystore Password: ", false);
callbackHandler.handle(new Callback[] { pcb });
ks.load(new FileInputStream(keystorePath), pcb.getPassword());
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Exception", e);
ks = null;
}
} else {
ks.load(null, null);
}
}
if (ks != null) {
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
try {
if (pcb == null) {
kmf.init(ks, null);
} else {
kmf.init(ks, pcb.getPassword());
pcb.clearPassword();
}
kms = kmf.getKeyManagers();
} catch (NullPointerException npe) {
LOGGER.log(Level.WARNING, "NullPointerException", npe);
}
}
// If the user didn't specify a SSLContext, use the default one
context = SSLContext.getInstance("TLS");
final SecureRandom secureRandom = new java.security.SecureRandom();
X509TrustManager customTrustManager = config.getCustomX509TrustManager();
if (daneVerifier != null) {
// User requested DANE verification.
daneVerifier.init(context, kms, customTrustManager, secureRandom);
} else {
TrustManager[] customTrustManagers = null;
if (customTrustManager != null) {
customTrustManagers = new TrustManager[] { customTrustManager };
}
context.init(kms, customTrustManagers, secureRandom);
}
}
Socket plain = socket;
// Secure the plain connection
socket = context.getSocketFactory().createSocket(plain, host, plain.getPort(), true);
final SSLSocket sslSocket = (SSLSocket) socket;
// Immediately set the enabled SSL protocols and ciphers. See SMACK-712 why this is
// important (at least on certain platforms) and it seems to be a good idea anyways to
// prevent an accidental implicit handshake.
TLSUtils.setEnabledProtocolsAndCiphers(sslSocket, config.getEnabledSSLProtocols(), config.getEnabledSSLCiphers());
// Initialize the reader and writer with the new secured version
initReaderAndWriter();
// Proceed to do the handshake
sslSocket.startHandshake();
if (daneVerifier != null) {
daneVerifier.finish(sslSocket);
}
final HostnameVerifier verifier = getConfiguration().getHostnameVerifier();
if (verifier == null) {
throw new IllegalStateException("No HostnameVerifier set. Use connectionConfiguration.setHostnameVerifier() to configure.");
} else if (!verifier.verify(getXMPPServiceDomain().toString(), sslSocket.getSession())) {
throw new CertificateException("Hostname verification of certificate failed. Certificate does not authenticate " + getXMPPServiceDomain());
}
// Set that TLS was successful
secureSocket = sslSocket;
}
Aggregations