Search in sources :

Example 81 with KeyManagementException

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);
    }
}
Also used : OkHttpClient(okhttp3.OkHttpClient) AccountItem(com.xabber.android.data.account.AccountItem) StanzaListener(org.jivesoftware.smack.StanzaListener) AccountJid(com.xabber.android.data.entity.AccountJid) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) Call(okhttp3.Call) UserJid(com.xabber.android.data.entity.UserJid) AccountJid(com.xabber.android.data.entity.AccountJid) DomainBareJid(org.jxmpp.jid.DomainBareJid) Jid(org.jxmpp.jid.Jid) Stanza(org.jivesoftware.smack.packet.Stanza) Request(okhttp3.Request) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) ExceptionCallback(org.jivesoftware.smack.ExceptionCallback) SmackException(org.jivesoftware.smack.SmackException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) XMPPException(org.jivesoftware.smack.XMPPException) MemorizingTrustManager(de.duenndns.ssl.MemorizingTrustManager) Response(okhttp3.Response) Callback(okhttp3.Callback) ExceptionCallback(org.jivesoftware.smack.ExceptionCallback) X509TrustManager(javax.net.ssl.X509TrustManager) Slot(com.xabber.xmpp.httpfileupload.Slot) File(java.io.File)

Example 82 with KeyManagementException

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());
}
Also used : MemorizingTrustManager(de.duenndns.ssl.MemorizingTrustManager) XMPPTCPConnection(org.jivesoftware.smack.tcp.XMPPTCPConnection) AllowAllHostnameVerifier(org.apache.http.conn.ssl.AllowAllHostnameVerifier) XMPPTCPConnectionConfiguration(org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyManagementException(java.security.KeyManagementException) NonNull(android.support.annotation.NonNull)

Example 83 with KeyManagementException

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);
    }
}
Also used : FileInputStream(java.io.FileInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) FileNotFoundException(java.io.FileNotFoundException) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) KeyManagementException(java.security.KeyManagementException) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) UnrecoverableKeyException(java.security.UnrecoverableKeyException) ByteArrayInputStream(java.io.ByteArrayInputStream) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) NoSuchProviderException(java.security.NoSuchProviderException)

Example 84 with KeyManagementException

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);
    }
}
Also used : ArrayList(java.util.ArrayList) List(java.util.List) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyManagementException(java.security.KeyManagementException)

Example 85 with KeyManagementException

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();
}
Also used : Path(java.nio.file.Path) InputStream(java.io.InputStream) ThreadContext(org.elasticsearch.common.util.concurrent.ThreadContext) RestClientBuilder(org.elasticsearch.client.RestClientBuilder) SSLIOSessionStrategy(org.apache.http.nio.conn.ssl.SSLIOSessionStrategy) CertificateException(java.security.cert.CertificateException) SSLContext(javax.net.ssl.SSLContext) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStore(java.security.KeyStore) KeyManagementException(java.security.KeyManagementException) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) Map(java.util.Map) Collections.singletonMap(java.util.Collections.singletonMap) BasicHeader(org.apache.http.message.BasicHeader)

Aggregations

KeyManagementException (java.security.KeyManagementException)157 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)111 SSLContext (javax.net.ssl.SSLContext)83 KeyStoreException (java.security.KeyStoreException)60 IOException (java.io.IOException)55 TrustManager (javax.net.ssl.TrustManager)45 CertificateException (java.security.cert.CertificateException)35 X509TrustManager (javax.net.ssl.X509TrustManager)28 SecureRandom (java.security.SecureRandom)27 X509Certificate (java.security.cert.X509Certificate)26 UnrecoverableKeyException (java.security.UnrecoverableKeyException)24 TrustManagerFactory (javax.net.ssl.TrustManagerFactory)24 KeyStore (java.security.KeyStore)22 KeyManager (javax.net.ssl.KeyManager)19 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)16 HostnameVerifier (javax.net.ssl.HostnameVerifier)15 KeyManagerFactory (javax.net.ssl.KeyManagerFactory)15 InputStream (java.io.InputStream)12 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)11 SSLSession (javax.net.ssl.SSLSession)10