Example usage for javax.net.ssl TrustManagerFactory getTrustManagers

List of usage examples for javax.net.ssl TrustManagerFactory getTrustManagers

Introduction

In this page you can find the example usage for javax.net.ssl TrustManagerFactory getTrustManagers.

Prototype

public final TrustManager[] getTrustManagers() 

Source Link

Document

Returns one trust manager for each type of trust material.

Usage

From source file:com.esri.geoevent.datastore.GeoEventDataStoreProxy.java

private HttpClientConnectionManager createConnectionManager() throws GeneralSecurityException, IOException {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null, null);/*from w  w w  .  j  a  v a  2 s.c  o m*/

    if (registry == null) {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);
        X509TrustManager x509TrustManager = null;
        for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
            if (trustManager instanceof X509TrustManager) {
                x509TrustManager = (X509TrustManager) trustManager;
                break;
            }
        }

        X509Certificate[] acceptedIssuers = x509TrustManager.getAcceptedIssuers();
        if (acceptedIssuers != null) {
            // If this is null, something is really wrong...
            int issuerNum = 1;
            for (X509Certificate cert : acceptedIssuers) {
                trustStore.setCertificateEntry("issuer" + issuerNum, cert);
                issuerNum++;
            }
        } else {
            LOG.log(Level.INFO, "Didn't find any new certificates to trust.");
        }

        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();

        sslContextBuilder.loadTrustMaterial(trustStore,
                new KnownArcGISCertificatesTrustStrategy(new ArrayList<>(trustedCerts)));
        SSLContext sslContext = sslContextBuilder.build();
        SSLContext.setDefault(sslContext);
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                new DataStoreProxyHostnameVerifier(new ArrayList<>(trustedCerts)));

        this.registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory).build();
    }
    return new PoolingHttpClientConnectionManager(registry);
}

From source file:org.wso2.carbon.event.adapter.rabbitmq.internal.util.RabbitMQInputEventAdapterListener.java

public RabbitMQInputEventAdapterListener(
        RabbitMQInputEventAdapterConnectionConfiguration rabbitMQInputEventAdapterConnectionConfiguration,
        InputEventAdapterConfiguration eventAdapterConfiguration,
        InputEventAdapterListener inputEventAdapterListener) {

    connectionFactory = new ConnectionFactory();
    this.rabbitMQInputEventAdapterConnectionConfiguration = rabbitMQInputEventAdapterConnectionConfiguration;
    this.queueName = eventAdapterConfiguration.getProperties()
            .get(RabbitMQInputEventAdapterConstants.RABBITMQ_QUEUE_NAME);
    this.exchangeName = eventAdapterConfiguration.getProperties()
            .get(RabbitMQInputEventAdapterConstants.RABBITMQ_EXCHANGE_NAME);
    this.exchangeType = eventAdapterConfiguration.getProperties()
            .get(RabbitMQInputEventAdapterConstants.RABBITMQ_EXCHANGE_TYPE);
    this.routeKey = eventAdapterConfiguration.getProperties()
            .get(RabbitMQInputEventAdapterConstants.RABBITMQ_QUEUE_ROUTING_KEY);
    this.consumerTagString = eventAdapterConfiguration.getProperties()
            .get(RabbitMQInputEventAdapterConstants.CONSUMER_TAG);
    this.adapterName = eventAdapterConfiguration.getName();
    this.eventAdapterListener = inputEventAdapterListener;
    this.tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
    workerState = STATE_STOPPED;/*from   w  w w  .  j  a  va  2 s  . c o m*/
    STATE_STARTED = 1;
    if (routeKey == null) {
        routeKey = queueName;
    }
    if (!eventAdapterConfiguration.getProperties()
            .get(RabbitMQInputEventAdapterConstants.RABBITMQ_CONNECTION_SSL_ENABLED).equals("false")) {
        try {
            boolean sslEnabled = Boolean.parseBoolean(eventAdapterConfiguration.getProperties()
                    .get(RabbitMQInputEventAdapterConstants.RABBITMQ_CONNECTION_SSL_ENABLED));
            if (sslEnabled) {
                String keyStoreLocation = eventAdapterConfiguration.getProperties()
                        .get(RabbitMQInputEventAdapterConstants.RABBITMQ_CONNECTION_SSL_KEYSTORE_LOCATION);
                String keyStoreType = eventAdapterConfiguration.getProperties()
                        .get(RabbitMQInputEventAdapterConstants.RABBITMQ_CONNECTION_SSL_KEYSTORE_TYPE);
                String keyStorePassword = eventAdapterConfiguration.getProperties()
                        .get(RabbitMQInputEventAdapterConstants.RABBITMQ_CONNECTION_SSL_KEYSTORE_PASSWORD);
                String trustStoreLocation = eventAdapterConfiguration.getProperties()
                        .get(RabbitMQInputEventAdapterConstants.RABBITMQ_CONNECTION_SSL_TRUSTSTORE_LOCATION);
                String trustStoreType = eventAdapterConfiguration.getProperties()
                        .get(RabbitMQInputEventAdapterConstants.RABBITMQ_CONNECTION_SSL_TRUSTSTORE_TYPE);
                String trustStorePassword = eventAdapterConfiguration.getProperties()
                        .get(RabbitMQInputEventAdapterConstants.RABBITMQ_CONNECTION_SSL_TRUSTSTORE_PASSWORD);
                String sslVersion = eventAdapterConfiguration.getProperties()
                        .get(RabbitMQInputEventAdapterConstants.RABBITMQ_CONNECTION_SSL_VERSION);

                if (StringUtils.isEmpty(keyStoreLocation) || StringUtils.isEmpty(keyStoreType)
                        || StringUtils.isEmpty(keyStorePassword) || StringUtils.isEmpty(trustStoreLocation)
                        || StringUtils.isEmpty(trustStoreType) || StringUtils.isEmpty(trustStorePassword)) {
                    if (log.isDebugEnabled()) {
                        log.debug("Truststore and keystore information is not provided");
                    }
                    if (StringUtils.isNotEmpty(sslVersion)) {
                        connectionFactory.useSslProtocol(sslVersion);
                    } else {
                        log.info("Proceeding with default SSL configuration");
                        connectionFactory.useSslProtocol();
                    }
                } else {
                    char[] keyPassphrase = keyStorePassword.toCharArray();
                    KeyStore ks = KeyStore.getInstance(keyStoreType);
                    ks.load(new FileInputStream(keyStoreLocation), keyPassphrase);

                    KeyManagerFactory kmf = KeyManagerFactory
                            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
                    kmf.init(ks, keyPassphrase);

                    char[] trustPassphrase = trustStorePassword.toCharArray();
                    KeyStore tks = KeyStore.getInstance(trustStoreType);
                    tks.load(new FileInputStream(trustStoreLocation), trustPassphrase);

                    TrustManagerFactory tmf = TrustManagerFactory
                            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
                    tmf.init(tks);

                    SSLContext context = SSLContext.getInstance(sslVersion);
                    context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

                    connectionFactory.useSslProtocol(context);
                }
            }
        } catch (IOException e) {
            handleException("TrustStore or KeyStore File path is incorrect. Specify KeyStore location or "
                    + "TrustStore location Correctly.", e);
        } catch (CertificateException e) {
            handleException("TrustStore or keyStore is not specified. So Security certificate"
                    + " Exception happened.  ", e);
        } catch (NoSuchAlgorithmException e) {
            handleException("Algorithm is not available in KeyManagerFactory class.", e);
        } catch (UnrecoverableKeyException e) {
            handleException("Unable to recover Key", e);
        } catch (KeyStoreException e) {
            handleException("Error in KeyStore or TrustStore Type", e);
        } catch (KeyManagementException e) {
            handleException("Error in Key Management", e);
        }
    }

    if (!StringUtils.isEmpty(eventAdapterConfiguration.getProperties()
            .get(RabbitMQInputEventAdapterConstants.RABBITMQ_FACTORY_HEARTBEAT))) {
        try {
            int heartbeatValue = Integer.parseInt(eventAdapterConfiguration.getProperties()
                    .get(RabbitMQInputEventAdapterConstants.RABBITMQ_FACTORY_HEARTBEAT));
            connectionFactory.setRequestedHeartbeat(heartbeatValue);
        } catch (NumberFormatException e) {
            log.warn("Number format error in reading heartbeat value. Proceeding with default");
        }
    }
    connectionFactory.setHost(rabbitMQInputEventAdapterConnectionConfiguration.getHostName());
    try {
        int port = Integer.parseInt(rabbitMQInputEventAdapterConnectionConfiguration.getPort());
        if (port > 0) {
            connectionFactory.setPort(port);
        }
    } catch (NumberFormatException e) {
        handleException("Number format error in port number", e);
    }
    connectionFactory.setUsername(rabbitMQInputEventAdapterConnectionConfiguration.getUsername());
    connectionFactory.setPassword(rabbitMQInputEventAdapterConnectionConfiguration.getPassword());
    if (!StringUtils.isEmpty(eventAdapterConfiguration.getProperties()
            .get(RabbitMQInputEventAdapterConstants.RABBITMQ_SERVER_VIRTUAL_HOST))) {
        connectionFactory.setVirtualHost(eventAdapterConfiguration.getProperties()
                .get(RabbitMQInputEventAdapterConstants.RABBITMQ_SERVER_VIRTUAL_HOST));
    }
    if (!StringUtils.isEmpty(eventAdapterConfiguration.getProperties()
            .get(RabbitMQInputEventAdapterConstants.RABBITMQ_CONNECTION_RETRY_COUNT))) {
        try {
            retryCountMax = Integer.parseInt(eventAdapterConfiguration.getProperties()
                    .get(RabbitMQInputEventAdapterConstants.RABBITMQ_CONNECTION_RETRY_COUNT));
        } catch (NumberFormatException e) {
            log.warn("Number format error in reading retry count value. Proceeding with default value (3)", e);
        }
    }
    if (!StringUtils.isEmpty(eventAdapterConfiguration.getProperties()
            .get(RabbitMQInputEventAdapterConstants.RABBITMQ_CONNECTION_RETRY_INTERVAL))) {
        try {
            retryInterval = Integer.parseInt(eventAdapterConfiguration.getProperties()
                    .get(RabbitMQInputEventAdapterConstants.RABBITMQ_CONNECTION_RETRY_INTERVAL));
        } catch (NumberFormatException e) {
            log.warn("Number format error in reading retry interval value. Proceeding with default value"
                    + " (30000ms)", e);
        }
    }
}

From source file:com.evolveum.midpoint.prism.crypto.ProtectorImpl.java

/**
 * @throws SystemException if jceks keystore is not available on {@link ProtectorImpl#getKeyStorePath}
 *//*from w  w w. j  a  v a  2 s  .c o  m*/
public void init() {
    InputStream stream = null;
    try {
        // Test if use file or classpath resource
        File f = new File(getKeyStorePath());
        if (f.exists()) {
            LOGGER.info("Using file keystore at {}", getKeyStorePath());
            if (!f.canRead()) {
                LOGGER.error("Provided keystore file {} is unreadable.", getKeyStorePath());
                throw new EncryptionException(
                        "Provided keystore file " + getKeyStorePath() + " is unreadable.");
            }
            stream = new FileInputStream(f);

            // Use class path keystore
        } else {
            LOGGER.warn("Using default keystore from classpath ({}).", getKeyStorePath());
            // Read from class path

            stream = ProtectorImpl.class.getClassLoader().getResourceAsStream(getKeyStorePath());
            // ugly dirty hack to have second chance to find keystore on
            // class path
            if (stream == null) {
                stream = ProtectorImpl.class.getClassLoader()
                        .getResourceAsStream("com/../../" + getKeyStorePath());
            }
        }
        // Test if we have valid stream
        if (stream == null) {
            throw new EncryptionException("Couldn't load keystore as resource '" + getKeyStorePath() + "'");
        }
        // Load keystore
        keyStore.load(stream, getKeyStorePassword().toCharArray());
        Enumeration<String> aliases = keyStore.aliases();
        Set<String> keyEntryAliasesInKeyStore = new HashSet<>();

        MessageDigest sha1;
        try {
            sha1 = MessageDigest.getInstance(KEY_DIGEST_TYPE);
        } catch (NoSuchAlgorithmException ex) {
            throw new EncryptionException(ex.getMessage(), ex);
        }

        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            try {
                if (!keyStore.isKeyEntry(alias)) {
                    LOGGER.trace("Alias {} is not a key entry and shall be skipped", alias);
                    continue;
                }
                keyEntryAliasesInKeyStore.add(alias);
                Key key = keyStore.getKey(alias, KEY_PASSWORD);
                if (!(key instanceof SecretKey)) {
                    continue;
                }
                final SecretKey secretKey = (SecretKey) key;
                LOGGER.trace("Found secret key for alias {}", alias);
                aliasToSecretKeyHashMap.put(alias, secretKey);

                final String digest = Base64.encode(sha1.digest(key.getEncoded()));
                LOGGER.trace("Calculated digest {} for key alias {}", digest, key);
                digestToSecretKeyHashMap.put(digest, secretKey);

            } catch (UnrecoverableKeyException ex) {
                LOGGER.trace("Couldn't recover key {} from keystore, reason: {}",
                        new Object[] { alias, ex.getMessage() });
            }
        }
        LOGGER.trace("Found {} aliases in keystore identified as secret keys", aliasToSecretKeyHashMap.size());
        stream.close();

        // Initialize trust manager list

        TrustManagerFactory tmFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmFactory.init(keyStore);
        trustManagers = new ArrayList<>();
        for (TrustManager trustManager : tmFactory.getTrustManagers()) {
            trustManagers.add(trustManager);
        }

        //init apache crypto library
        Init.init();

    } catch (Exception ex) {
        LOGGER.error("Unable to work with keystore {}, reason {}.",
                new Object[] { getKeyStorePath(), ex.getMessage() }, ex);
        throw new SystemException(ex.getMessage(), ex);
    }

    randomNumberGenerator = new SecureRandom();
}

From source file:org.codice.ddf.cxf.client.impl.SecureCxfClientFactoryImpl.java

@SuppressWarnings("squid:S3776")
private void configureConduit(ClientConfiguration clientConfig) {
    HTTPConduit httpConduit = clientConfig.getHttpConduit();
    if (httpConduit == null) {
        LOGGER.info("HTTPConduit was null for {}. Unable to configure security.", this);
        return;//from  w w w . j  a v  a  2 s. co  m
    }

    if (allowRedirects) {
        HTTPClientPolicy clientPolicy = httpConduit.getClient();
        if (clientPolicy != null) {
            clientPolicy.setAutoRedirect(true);
            Bus bus = clientConfig.getBus();
            if (bus != null) {
                bus.getProperties().put(AUTO_REDIRECT_ALLOW_REL_URI, true);
                bus.getProperties().put(AUTO_REDIRECT_MAX_SAME_URI_COUNT, getSameUriRedirectMax());
            }
        }
    }

    TLSClientParameters tlsParams = httpConduit.getTlsClientParameters();
    if (tlsParams == null) {
        tlsParams = new TLSClientParameters();
    }

    tlsParams.setDisableCNCheck(disableCnCheck);

    tlsParams.setUseHttpsURLConnectionDefaultHostnameVerifier(!disableCnCheck);
    String cipherSuites = System.getProperty("https.cipherSuites");
    if (cipherSuites != null) {
        tlsParams.setCipherSuites(Arrays.asList(cipherSuites.split(",")));
    }

    KeyStore keyStore = null;
    KeyStore trustStore = null;
    try {
        keyStore = SecurityConstants.newKeystore();
        trustStore = SecurityConstants.newTruststore();
    } catch (KeyStoreException e) {
        LOGGER.debug("Unable to create keystore instance of type {}",
                System.getProperty(SecurityConstants.KEYSTORE_TYPE), e);
    }
    Path keyStoreFile;
    if (keyInfo != null && StringUtils.isNotBlank(keyInfo.getKeystorePath())) {
        keyStoreFile = Paths.get(keyInfo.getKeystorePath());
    } else {
        keyStoreFile = Paths.get(SecurityConstants.getKeystorePath());
    }

    Path trustStoreFile = Paths.get(SecurityConstants.getTruststorePath());
    String ddfHome = System.getProperty("ddf.home");
    if (ddfHome != null) {
        Path ddfHomePath = Paths.get(ddfHome);
        if (!keyStoreFile.isAbsolute()) {
            keyStoreFile = Paths.get(ddfHomePath.toString(), keyStoreFile.toString());
        }
        if (!trustStoreFile.isAbsolute()) {
            trustStoreFile = Paths.get(ddfHomePath.toString(), trustStoreFile.toString());
        }
    }
    String keyStorePassword = SecurityConstants.getKeystorePassword();
    String trustStorePassword = SecurityConstants.getTruststorePassword();
    if (!Files.isReadable(keyStoreFile) || !Files.isReadable(trustStoreFile)) {
        LOGGER.debug("Unable to read system key/trust store files: [ {} ] [ {} ]", keyStoreFile,
                trustStoreFile);
        return;
    }
    try (InputStream kfis = Files.newInputStream(keyStoreFile)) {
        if (keyStore != null) {
            keyStore.load(kfis, keyStorePassword.toCharArray());
        }
    } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
        LOGGER.debug("Unable to load system key file.", e);
    }
    try (InputStream tfis = Files.newInputStream(trustStoreFile)) {
        if (trustStore != null) {
            trustStore.load(tfis, trustStorePassword.toCharArray());
        }
    } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
        LOGGER.debug("Unable to load system trust file.", e);
    }

    KeyManager[] keyManagers = null;
    try {
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
        keyManagers = keyManagerFactory.getKeyManagers();
        tlsParams.setKeyManagers(keyManagers);
    } catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException e) {
        LOGGER.debug("Unable to initialize KeyManagerFactory.", e);
    }

    TrustManager[] trustManagers = null;
    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        trustManagers = trustManagerFactory.getTrustManagers();
        tlsParams.setTrustManagers(trustManagers);
    } catch (NoSuchAlgorithmException | KeyStoreException e) {
        LOGGER.debug("Unable to initialize TrustManagerFactory.", e);
    }

    if (keyInfo != null) {
        LOGGER.trace("Using keystore file: {}, alias: {}", keyStoreFile, keyInfo.getAlias());
        tlsParams.setUseHttpsURLConnectionDefaultSslSocketFactory(false);
        tlsParams.setCertAlias(keyInfo.getAlias());
        try {
            if (keyManagers == null) {
                throw new KeyManagementException("keyManagers was null");
            }

            boolean validProtocolFound = false;
            String validProtocolsStr = System.getProperty("jdk.tls.client.protocols");
            if (StringUtils.isNotBlank(validProtocolsStr)) {
                String[] validProtocols = validProtocolsStr.split(",");
                for (String validProtocol : validProtocols) {
                    if (validProtocol.equals(sslProtocol)) {
                        validProtocolFound = true;
                        break;
                    }
                }
                if (!validProtocolFound) {
                    LOGGER.error("{} is not in list of valid SSL protocols {}", sslProtocol, validProtocolsStr);
                }

            } else {
                validProtocolFound = true;
            }
            if (validProtocolFound) {
                tlsParams.setSSLSocketFactory(
                        getSSLSocketFactory(sslProtocol, keyInfo.getAlias(), keyManagers, trustManagers));
            }
        } catch (KeyManagementException | NoSuchAlgorithmException e) {
            LOGGER.debug("Unable to override default SSL Socket Factory", e);
        }
    } else {
        tlsParams.setUseHttpsURLConnectionDefaultSslSocketFactory(true);
        tlsParams.setCertAlias(SystemBaseUrl.INTERNAL.getHost());
    }

    httpConduit.setTlsClientParameters(tlsParams);
}

From source file:de.duenndns.ssl.MemorizingTrustManager.java

X509TrustManager getTrustManager(KeyStore ks) {
    try {//from  ww w. j  av  a  2 s.  c  o m
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
        tmf.init(ks);
        for (TrustManager t : tmf.getTrustManagers()) {
            if (t instanceof X509TrustManager) {
                return (X509TrustManager) t;
            }
        }
    } catch (Exception e) {
        // Here, we are covering up errors. It might be more useful
        // however to throw them out of the constructor so the
        // embedding app knows something went wrong.
        LOGGER.log(Level.SEVERE, "getTrustManager(" + ks + ")", e);
    }
    return null;
}

From source file:org.wso2.carbon.identity.sso.agent.bean.SSOAgentConfig.java

private TrustManager[] doSSLVerification() throws Exception {
    TrustManager[] trustManagers = null;
    if (this.getEnableSSLVerification()) {
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(this.getKeyStore());
        trustManagers = tmf.getTrustManagers();
    } else {//from   w  w  w.  j  a va  2s.c  om
        // Create a trust manager that does not validate certificate chains
        trustManagers = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }
        } };
    }
    return trustManagers;
}

From source file:com.twinsoft.convertigo.engine.MySSLSocketFactory.java

private SSLContext createEasySSLContext()
        throws NoSuchProviderException, NoSuchAlgorithmException, KeyManagementException,
        UnrecoverableKeyException, KeyStoreException, CertificateException, IOException {
    Engine.logCertificateManager.debug("(MySSLSocketFactory) Creating SSL context");

    String algorithm = KeyManagerFactory.getDefaultAlgorithm();
    Engine.logCertificateManager.debug("(MySSLSocketFactory) Using KeyManager algorithm " + algorithm);

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);

    String keyStoreType = keyStore.endsWith(".pkcs11") ? "pkcs11" : "pkcs12";
    Engine.logCertificateManager.debug("(MySSLSocketFactory) Key store type: " + keyStoreType);

    String alias = null;/*from  ww w  .  j  a va2s.c o m*/
    KeyStore ks, ts;
    char[] passPhrase;

    if (keyStore.equals("") || (keyStore.endsWith(".udv"))) {
        ks = KeyStore.getInstance(keyStoreType);
        ks.load(null, keyStorePassword.toCharArray());
        kmf.init(ks, null);
    } else {
        File file = new File(keyStore);

        Properties properties = new Properties();
        properties.load(
                new FileInputStream(Engine.CERTIFICATES_PATH + CertificateManager.STORES_PROPERTIES_FILE_NAME));
        String p = properties.getProperty(file.getName(), "");
        int i = p.indexOf('/');
        if (i != -1) {
            alias = p.substring(i + 1);
        }

        if (keyStoreType.equals("pkcs11")) {
            String providerName = file.getName();
            providerName = "SunPKCS11-" + providerName.substring(0, providerName.lastIndexOf('.'));
            Engine.logCertificateManager.debug("(MySSLSocketFactory) Provider name: '" + providerName + "'");

            String pinCode;
            if (i == -1) {
                pinCode = Crypto2.decodeFromHexString(p);
            } else {
                pinCode = Crypto2.decodeFromHexString(p.substring(0, i));
            }

            Engine.logCertificateManager.debug("(MySSLSocketFactory) PIN code: " + pinCode);

            ks = KeyStore.getInstance("pkcs11", providerName);
            ks.load((InputStream) null, pinCode.toCharArray());
            kmf.init(ks, null);
        } else {
            ks = KeyStore.getInstance(keyStoreType);
            passPhrase = keyStorePassword.toCharArray();
            ks.load(new FileInputStream(keyStore), passPhrase);
            kmf.init(ks, passPhrase);
        }
    }
    Engine.logCertificateManager.debug("(MySSLSocketFactory) Client alias: "
            + (alias == null ? "<to be chosen by the security implementor>" : alias));

    ts = KeyStore.getInstance("jks");
    passPhrase = trustStorePassword.toCharArray();
    if (trustStore.equals(""))
        ts.load(null, passPhrase);
    else
        ts.load(new FileInputStream(trustStore), passPhrase);

    algorithm = TrustManagerFactory.getDefaultAlgorithm();
    Engine.logCertificateManager.debug("(MySSLSocketFactory) Using TrustManager algorithm " + algorithm);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
    tmf.init(ts);

    TrustManager[] tm = { TRUST_MANAGER };

    MyX509KeyManager xkm = new MyX509KeyManager((X509KeyManager) kmf.getKeyManagers()[0], ks, ts, alias);

    Engine.logCertificateManager
            .debug("(MySSLSocketFactory) trusting all certificates : " + trustAllServerCertificates);

    //SSLContext context = SSLContext.getInstance("SSLv3");
    SSLContext context = SSLContext.getInstance("TLS");
    if (trustAllServerCertificates)
        context.init(new KeyManager[] { xkm }, tm, null);
    else
        context.init(new KeyManager[] { xkm }, tmf.getTrustManagers(), null);

    Engine.logCertificateManager.debug("(MySSLSocketFactory) SSL context created: " + context.getProtocol());
    return context;
}

From source file:org.alfresco.encryption.AlfrescoKeyStoreImpl.java

/**
 * {@inheritDoc}//  www.j a  v  a 2 s.c om
 */
@Override
public TrustManager[] createTrustManagers() {
    KeyInfoManager keyInfoManager = null;

    try {
        keyInfoManager = getKeyInfoManager(getKeyMetaDataFileLocation());
        KeyStore ks = loadKeyStore(getKeyStoreParameters(), keyInfoManager);

        logger.debug("Initializing trust managers");
        TrustManagerFactory tmfactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmfactory.init(ks);
        return tmfactory.getTrustManagers();
    } catch (Throwable e) {
        throw new AlfrescoRuntimeException("Unable to create key manager", e);
    } finally {
        if (keyInfoManager != null) {
            keyInfoManager.clear();
        }
    }
}

From source file:ddf.catalog.source.opensearch.SecureRemoteConnectionImpl.java

/**
 * Creates a new SSLSocketFactory from a truststore and keystore. This is used during SSL
 * communications with the server./*ww w .  ja  va2  s.  c  o  m*/
 * 
 * @param trustStoreLoc
 *            File path to the truststore.
 * @param trustStorePass
 *            Password to the truststore.
 * @param keyStoreLoc
 *            File path to the keystore.
 * @param keyStorePass
 *            Password to the keystore.
 * @return new SSLSocketFactory instance containing the trust and key stores.
 * @throws KeyStoreException
 * @throws IOException
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws UnrecoverableKeyException
 * @throws KeyManagementException
 */
public SSLSocketFactory createSocket(String trustStoreLoc, String trustStorePass, String keyStoreLoc,
        String keyStorePass) throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
        IOException, UnrecoverableKeyException, KeyManagementException {
    String methodName = "createSocket";
    LOGGER.debug("ENTERING: " + methodName);

    LOGGER.debug("trustStoreLoc = " + trustStoreLoc);
    FileInputStream trustFIS = new FileInputStream(trustStoreLoc);
    LOGGER.debug("keyStoreLoc = " + keyStoreLoc);
    FileInputStream keyFIS = new FileInputStream(keyStoreLoc);

    // truststore stuff
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    try {
        LOGGER.debug("Loading trustStore");
        trustStore.load(trustFIS, trustStorePass.toCharArray());
    } finally {
        IOUtils.closeQuietly(trustFIS);
    }

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(trustStore);
    LOGGER.debug("trust manager factory initialized");

    // keystore stuff
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    try {
        LOGGER.debug("Loading keyStore");
        keyStore.load(keyFIS, keyStorePass.toCharArray());
    } finally {
        IOUtils.closeQuietly(keyFIS);
    }
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(keyStore, keyStorePass.toCharArray());
    LOGGER.debug("key manager factory initialized");

    // ssl context
    SSLContext sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    LOGGER.debug("EXITING: " + methodName);

    return sslCtx.getSocketFactory();
}