use of java.security.KeyManagementException in project xabber-android by redsolution.
the class HttpFileUploadManager method uploadFile.
public void uploadFile(final AccountJid account, final UserJid user, final String filePath) {
final Jid uploadServerUrl = uploadServers.get(account);
if (uploadServerUrl == null) {
return;
}
AccountItem accountItem = AccountManager.getInstance().getAccount(account);
if (accountItem == null) {
return;
}
final File file = new File(filePath);
final com.xabber.xmpp.httpfileupload.Request httpFileUpload = new com.xabber.xmpp.httpfileupload.Request();
httpFileUpload.setFilename(file.getName());
httpFileUpload.setSize(String.valueOf(file.length()));
httpFileUpload.setTo(uploadServerUrl);
try {
accountItem.getConnection().sendIqWithResponseCallback(httpFileUpload, new StanzaListener() {
@Override
public void processStanza(Stanza packet) throws SmackException.NotConnectedException, InterruptedException {
if (!(packet instanceof Slot)) {
return;
}
uploadFileToSlot(account, (Slot) packet);
}
private void uploadFileToSlot(final AccountJid account, final Slot slot) {
SSLSocketFactory sslSocketFactory = null;
MemorizingTrustManager mtm = CertificateManager.getInstance().getNewFileUploadManager(account);
final SSLContext sslContext;
try {
sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new X509TrustManager[] { mtm }, new java.security.SecureRandom());
sslSocketFactory = sslContext.getSocketFactory();
} catch (NoSuchAlgorithmException | KeyManagementException e) {
return;
}
OkHttpClient client = new OkHttpClient().newBuilder().sslSocketFactory(sslSocketFactory).hostnameVerifier(mtm.wrapHostnameVerifier(new org.apache.http.conn.ssl.StrictHostnameVerifier())).writeTimeout(5, TimeUnit.MINUTES).connectTimeout(5, TimeUnit.MINUTES).readTimeout(5, TimeUnit.MINUTES).build();
Request request = new Request.Builder().url(slot.getPutUrl()).put(RequestBody.create(CONTENT_TYPE, file)).build();
final String fileMessageId;
fileMessageId = MessageManager.getInstance().createFileMessage(account, user, file);
LogManager.i(HttpFileUploadManager.this, "starting upload file to " + slot.getPutUrl() + " size " + file.length());
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
LogManager.i(HttpFileUploadManager.this, "onFailure " + e.getMessage());
MessageManager.getInstance().updateMessageWithError(fileMessageId, e.toString());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
LogManager.i(HttpFileUploadManager.this, "onResponse " + response.isSuccessful() + " " + response.body().string());
if (response.isSuccessful()) {
MessageManager.getInstance().updateFileMessage(account, user, fileMessageId, slot.getGetUrl());
} else {
MessageManager.getInstance().updateMessageWithError(fileMessageId, response.message());
}
}
});
}
}, new ExceptionCallback() {
@Override
public void processException(Exception exception) {
LogManager.i(this, "On HTTP file upload slot error");
LogManager.exception(this, exception);
Application.getInstance().onError(R.string.http_file_upload_slot_error);
}
});
} catch (SmackException.NotConnectedException | InterruptedException e) {
LogManager.exception(this, e);
}
}
use of java.security.KeyManagementException in project xabber-android by redsolution.
the class ConnectionBuilder method build.
@NonNull
public static XMPPTCPConnection build(AccountJid account, @NonNull final ConnectionSettings connectionSettings) {
XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder();
builder.setXmppDomain(connectionSettings.getServerName());
if (connectionSettings.isCustomHostAndPort()) {
setCustomHost(connectionSettings, builder);
builder.setPort(connectionSettings.getPort());
}
builder.setDebuggerEnabled(true);
builder.setSecurityMode(connectionSettings.getTlsMode().getSecurityMode());
builder.setCompressionEnabled(connectionSettings.useCompression());
builder.setSendPresence(false);
builder.setUsernameAndPassword(connectionSettings.getUserName(), connectionSettings.getPassword());
builder.setResource(connectionSettings.getResource());
builder.setProxyInfo(getProxyInfo(connectionSettings));
try {
LogManager.i(LOG_TAG, "SettingsManager.securityCheckCertificate: " + SettingsManager.securityCheckCertificate());
if (SettingsManager.securityCheckCertificate()) {
SSLContext sslContext = SSLContext.getInstance("TLS");
MemorizingTrustManager mtm = CertificateManager.getInstance().getNewMemorizingTrustManager(account);
sslContext.init(null, new X509TrustManager[] { mtm }, new java.security.SecureRandom());
builder.setCustomSSLContext(sslContext);
builder.setHostnameVerifier(mtm.wrapHostnameVerifier(new CustomDomainVerifier()));
} else {
TLSUtils.acceptAllCertificates(builder);
builder.setHostnameVerifier(new AllowAllHostnameVerifier());
}
} catch (NoSuchAlgorithmException | KeyManagementException e) {
LogManager.exception(LOG_TAG, e);
}
// if account have token
if (connectionSettings.getToken() != null && !connectionSettings.getToken().isEmpty() && connectionSettings.getPassword() != null && connectionSettings.getPassword().isEmpty()) {
// then enable only SASLXOauth2Mechanism
builder.addEnabledSaslMechanism(SASLXOauth2Mechanism.NAME);
// and set token as password
builder.setUsernameAndPassword(connectionSettings.getUserName(), connectionSettings.getToken());
}
LogManager.i(LOG_TAG, "new XMPPTCPConnection " + connectionSettings.getServerName());
return new XMPPTCPConnection(builder.build());
}
use of java.security.KeyManagementException 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.KeyManagementException in project tomcat by apache.
the class JNDIRealm method createSSLContextFactoryFromProtocol.
private SSLSocketFactory createSSLContextFactoryFromProtocol(String protocol) {
try {
SSLContext sslContext;
if (protocol != null) {
sslContext = SSLContext.getInstance(protocol);
sslContext.init(null, null, null);
} else {
sslContext = SSLContext.getDefault();
}
return sslContext.getSocketFactory();
} catch (NoSuchAlgorithmException | KeyManagementException e) {
List<String> allowedProtocols = Arrays.asList(getSupportedSslProtocols());
throw new IllegalArgumentException(sm.getString("jndiRealm.invalidSslProtocol", protocol, allowedProtocols), e);
}
}
use of java.security.KeyManagementException in project elasticsearch by elastic.
the class ESRestTestCase method buildClient.
protected RestClient buildClient(Settings settings, HttpHost[] hosts) throws IOException {
RestClientBuilder builder = RestClient.builder(hosts);
String keystorePath = settings.get(TRUSTSTORE_PATH);
if (keystorePath != null) {
final String keystorePass = settings.get(TRUSTSTORE_PASSWORD);
if (keystorePass == null) {
throw new IllegalStateException(TRUSTSTORE_PATH + " is provided but not " + TRUSTSTORE_PASSWORD);
}
Path path = PathUtils.get(keystorePath);
if (!Files.exists(path)) {
throw new IllegalStateException(TRUSTSTORE_PATH + " is set but points to a non-existing file");
}
try {
KeyStore keyStore = KeyStore.getInstance("jks");
try (InputStream is = Files.newInputStream(path)) {
keyStore.load(is, keystorePass.toCharArray());
}
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keyStore, null).build();
SSLIOSessionStrategy sessionStrategy = new SSLIOSessionStrategy(sslcontext);
builder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLStrategy(sessionStrategy));
} catch (KeyStoreException | NoSuchAlgorithmException | KeyManagementException | CertificateException e) {
throw new RuntimeException("Error setting up ssl", e);
}
}
try (ThreadContext threadContext = new ThreadContext(settings)) {
Header[] defaultHeaders = new Header[threadContext.getHeaders().size()];
int i = 0;
for (Map.Entry<String, String> entry : threadContext.getHeaders().entrySet()) {
defaultHeaders[i++] = new BasicHeader(entry.getKey(), entry.getValue());
}
builder.setDefaultHeaders(defaultHeaders);
}
return builder.build();
}
Aggregations