Example usage for javax.net.ssl TrustManagerFactory init

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

Introduction

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

Prototype

public final void init(ManagerFactoryParameters spec) throws InvalidAlgorithmParameterException 

Source Link

Document

Initializes this factory with a source of provider-specific trust material.

Usage

From source file:org.apache.nifi.processors.grpc.InvokeGRPC.java

/**
 * Whenever this processor is triggered, we need to construct a client in order to communicate
 * with the configured gRPC service.// w  ww .ja v  a  2  s .c  o m
 *
 * @param context the processor context
 */
@OnScheduled
public void initializeClient(final ProcessContext context) throws Exception {

    channelReference.set(null);
    blockingStubReference.set(null);
    final ComponentLog logger = getLogger();

    final String host = context.getProperty(PROP_SERVICE_HOST).getValue();
    final int port = context.getProperty(PROP_SERVICE_PORT).asInteger();
    final Integer maxMessageSize = context.getProperty(PROP_MAX_MESSAGE_SIZE).asDataSize(DataUnit.B).intValue();
    String userAgent = USER_AGENT_PREFIX;
    try {
        userAgent += "_" + InetAddress.getLocalHost().getHostName();
    } catch (final UnknownHostException e) {
        logger.warn("Unable to determine local hostname. Defaulting gRPC user agent to {}.",
                new Object[] { USER_AGENT_PREFIX }, e);
    }

    final NettyChannelBuilder nettyChannelBuilder = NettyChannelBuilder.forAddress(host, port)
            // supports both gzip and plaintext, but will compress by default.
            .compressorRegistry(CompressorRegistry.getDefaultInstance())
            .decompressorRegistry(DecompressorRegistry.getDefaultInstance())
            .maxInboundMessageSize(maxMessageSize).userAgent(userAgent);

    // configure whether or not we're using secure comms
    final boolean useSecure = context.getProperty(PROP_USE_SECURE).asBoolean();
    final SSLContextService sslContextService = context.getProperty(PROP_SSL_CONTEXT_SERVICE)
            .asControllerService(SSLContextService.class);
    final SSLContext sslContext = sslContextService == null ? null
            : sslContextService.createSSLContext(SSLContextService.ClientAuth.NONE);

    if (useSecure && sslContext != null) {
        SslContextBuilder sslContextBuilder = GrpcSslContexts.forClient();
        if (StringUtils.isNotBlank(sslContextService.getKeyStoreFile())) {
            final KeyManagerFactory keyManagerFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm(), sslContext.getProvider());
            final KeyStore keyStore = KeyStore.getInstance(sslContextService.getKeyStoreType());
            try (final InputStream is = new FileInputStream(sslContextService.getKeyStoreFile())) {
                keyStore.load(is, sslContextService.getKeyStorePassword().toCharArray());
            }
            keyManagerFactory.init(keyStore, sslContextService.getKeyStorePassword().toCharArray());
            sslContextBuilder.keyManager(keyManagerFactory);
        }

        if (StringUtils.isNotBlank(sslContextService.getTrustStoreFile())) {
            final TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm(), sslContext.getProvider());
            final KeyStore trustStore = KeyStore.getInstance(sslContextService.getTrustStoreType());
            try (final InputStream is = new FileInputStream(sslContextService.getTrustStoreFile())) {
                trustStore.load(is, sslContextService.getTrustStorePassword().toCharArray());
            }
            trustManagerFactory.init(trustStore);
            sslContextBuilder.trustManager(trustManagerFactory);
        }
        nettyChannelBuilder.sslContext(sslContextBuilder.build());

    } else {
        nettyChannelBuilder.usePlaintext(true);
    }

    final ManagedChannel channel = nettyChannelBuilder.build();
    final FlowFileServiceGrpc.FlowFileServiceBlockingStub blockingStub = FlowFileServiceGrpc
            .newBlockingStub(channel);
    channelReference.set(channel);
    blockingStubReference.set(blockingStub);
}

From source file:org.gvnix.service.roo.addon.addon.security.SecurityServiceImpl.java

/**
 * Get certificates in the chain of the host server and import them.
 * <p>// w  ww  .  ja va 2  s .  co m
 * Tries to get the certificates in the certificates chain of the host
 * server and import them to:
 * <ol>
 * <li>A custom keystore in <code>SRC_MAIN_RESOURCES/gvnix-cacerts</code></li>
 * <li>The JVM cacerts keystore in
 * <code>$JAVA_HOME/jre/lib/security/cacerts</code>. Here we can have a
 * problem if JVM <code>cacerts</code> file is not writable by the user due
 * to file permissions. In this case we throw an exception informing about
 * the error.</li>
 * </ol>
 * </p>
 * <p>
 * With that operation we can try again to get the WSDL.<br/>
 * Also it exports the chain certificates to <code>.cer</code> files in
 * <code>SRC_MAIN_RESOURCES</code>, so the developer can distribute them for
 * its installation in other environments or just in case we reach the
 * problem with the JVM <code>cacerts</code> file permissions.
 * </p>
 * 
 * @see GvNix509TrustManager#saveCertFile(String, X509Certificate,
 *      FileManager, PathResolver)
 * @see <a href=
 *      "http://download.oracle.com/javase/6/docs/technotes/tools/solaris/keytool.html"
 *      >Java SE keytool</a>.
 */
protected Document installCertificates(String loc, String pass)
        throws NoSuchAlgorithmException, KeyStoreException, Exception, KeyManagementException,
        MalformedURLException, IOException, UnknownHostException, SocketException, SAXException {

    // Create a SSL context
    SSLContext context = SSLContext.getInstance("TLS");
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

    // Passphrase of the keystore: "changeit" by default
    char[] passArray = (StringUtils.isNotBlank(pass) ? pass.toCharArray() : "changeit".toCharArray());

    // Get the project keystore and copy it from JVM if not exists
    File keystore = getProjectKeystore();

    tmf.init(GvNix509TrustManager.loadKeyStore(keystore, passArray));

    X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
    GvNix509TrustManager tm = new GvNix509TrustManager(defaultTrustManager);
    context.init(null, new TrustManager[] { tm }, null);
    SSLSocketFactory factory = context.getSocketFactory();

    // Open URL location (default 443 port if not defined)
    URL url = new URL(loc);
    String host = url.getHost();
    int port = url.getPort() == -1 ? 443 : url.getPort();
    SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
    socket.setSoTimeout(10000);

    Document doc = null;
    try {

        socket.startHandshake();
        URLConnection connection = url.openConnection();
        if (connection instanceof HttpsURLConnection) {
            ((HttpsURLConnection) connection).setSSLSocketFactory(factory);
        }

        doc = XmlUtils.getDocumentBuilder().parse(connection.getInputStream());

        socket.close();

    } catch (SSLException ssle) {

        // Get needed certificates for this host
        getCerts(tm, host, keystore, passArray);
        doc = getWsdl(loc, pass);

    } catch (IOException ioe) {

        invalidHostCert(passArray, keystore, tm, host);
    }

    Validate.notNull(doc, "No valid document format");
    return doc;
}

From source file:com.photon.phresco.framework.rest.api.util.FrameworkServiceUtil.java

public static List<CertificateInfo> getCertificate(String host, int port) throws PhrescoException {
    List<CertificateInfo> certificates = new ArrayList<CertificateInfo>();
    CertificateInfo info;/* ww w .  j  a v  a2 s. c o m*/
    try {
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        SSLContext context = SSLContext.getInstance("TLS");
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
        SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
        context.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory factory = context.getSocketFactory();
        SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
        socket.setSoTimeout(10000);
        try {
            socket.startHandshake();
            socket.close();
        } catch (SSLException e) {

        }
        X509Certificate[] chain = tm.chain;
        for (int i = 0; i < chain.length; i++) {
            X509Certificate x509Certificate = chain[i];
            String subjectDN = x509Certificate.getSubjectDN().getName();
            String[] split = subjectDN.split(",");
            info = new CertificateInfo();
            info.setSubjectDN(subjectDN);
            info.setDisplayName(split[0]);
            info.setCertificate(x509Certificate);
            certificates.add(info);
        }
    } catch (Exception e) {
        throw new PhrescoException(e);
    }
    return certificates;
}

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

/**
 * {@inheritDoc}//from ww  w.  ja  va2  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:org.apache.bookkeeper.tls.TLSContextFactory.java

private TrustManagerFactory initTrustManagerFactory(String trustStoreType, String trustStoreLocation,
        String trustStorePasswordPath) throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
        IOException, SecurityException {
    TrustManagerFactory tmf;

    if (Strings.isNullOrEmpty(trustStoreLocation)) {
        LOG.error("Trust Store location cannot be empty!");
        throw new SecurityException("Trust Store location cannot be empty!");
    }/*from ww w .j  av a2s .  c  om*/

    String trustStorePassword = "";
    if (!Strings.isNullOrEmpty(trustStorePasswordPath)) {
        trustStorePassword = getPasswordFromFile(trustStorePasswordPath);
    }

    // Initialize trust file
    KeyStore ts = loadKeyStore(trustStoreType, trustStoreLocation, trustStorePassword);
    tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ts);

    return tmf;
}

From source file:org.deviceconnect.android.message.DevicePluginContext.java

/**
 * SSLContext ?????.// w ww .  ja  v a  2s.  co m
 * <p>
 * ? Web ?????Manager???????????SSLContext ???
 * </p>
 * @param keyStore 
 * @return SSLContext?
 * @throws GeneralSecurityException SSLContext???????
 */
protected SSLContext createSSLContext(final KeyStore keyStore) throws GeneralSecurityException {
    SSLContext sslContext = SSLContext.getInstance("TLS");
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, "0000".toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
            new SecureRandom());
    return sslContext;
}

From source file:com.predic8.membrane.core.transport.ssl.SSLContext.java

public SSLContext(SSLParser sslParser, ResolverMap resourceResolver, String baseLocation) {
    this.sslParser = sslParser;
    try {/*from   w ww  . j  av a 2 s .co m*/
        String algorihm = KeyManagerFactory.getDefaultAlgorithm();
        if (sslParser.getAlgorithm() != null)
            algorihm = sslParser.getAlgorithm();

        KeyManagerFactory kmf = null;
        String keyStoreType = "JKS";
        if (sslParser.getKeyStore() != null) {
            if (sslParser.getKeyStore().getKeyAlias() != null)
                throw new InvalidParameterException("keyAlias is not yet supported.");
            char[] keyPass = "changeit".toCharArray();
            if (sslParser.getKeyStore().getKeyPassword() != null)
                keyPass = sslParser.getKeyStore().getKeyPassword().toCharArray();

            if (sslParser.getKeyStore().getType() != null)
                keyStoreType = sslParser.getKeyStore().getType();
            KeyStore ks = openKeyStore(sslParser.getKeyStore(), "JKS", keyPass, resourceResolver, baseLocation);
            kmf = KeyManagerFactory.getInstance(algorihm);
            kmf.init(ks, keyPass);

            Enumeration<String> aliases = ks.aliases();
            while (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();
                if (ks.isKeyEntry(alias)) {
                    // first key is used by the KeyManagerFactory
                    Certificate c = ks.getCertificate(alias);
                    if (c instanceof X509Certificate) {
                        X509Certificate x = (X509Certificate) c;

                        dnsNames = new ArrayList<String>();

                        Collection<List<?>> subjectAlternativeNames = x.getSubjectAlternativeNames();
                        if (subjectAlternativeNames != null)
                            for (List<?> l : subjectAlternativeNames) {
                                if (l.get(0) instanceof Integer && ((Integer) l.get(0) == 2))
                                    dnsNames.add(l.get(1).toString());
                            }
                    }
                    break;
                }
            }

        }
        TrustManagerFactory tmf = null;
        if (sslParser.getTrustStore() != null) {
            String trustAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            if (sslParser.getTrustStore().getAlgorithm() != null)
                trustAlgorithm = sslParser.getTrustStore().getAlgorithm();
            KeyStore ks = openKeyStore(sslParser.getTrustStore(), keyStoreType, null, resourceResolver,
                    baseLocation);
            tmf = TrustManagerFactory.getInstance(trustAlgorithm);
            tmf.init(ks);
        }

        TrustManager[] tms = tmf != null ? tmf.getTrustManagers()
                : null /* trust anyone: new TrustManager[] { new NullTrustManager() } */;
        if (sslParser.isIgnoreTimestampCheckFailure())
            tms = new TrustManager[] { new TrustManagerWrapper(tms, true) };

        if (sslParser.getProtocol() != null)
            sslc = javax.net.ssl.SSLContext.getInstance(sslParser.getProtocol());
        else
            sslc = javax.net.ssl.SSLContext.getInstance("TLS");

        sslc.init(kmf != null ? kmf.getKeyManagers() : null, tms, null);

        if (sslParser.getCiphers() != null) {
            ciphers = sslParser.getCiphers().split(",");
            Set<String> supportedCiphers = Sets.newHashSet(sslc.getSocketFactory().getSupportedCipherSuites());
            for (String cipher : ciphers) {
                if (!supportedCiphers.contains(cipher))
                    throw new InvalidParameterException("Unknown cipher " + cipher);
                if (cipher.contains("_RC4_"))
                    log.warn("Cipher " + cipher + " uses RC4, which is deprecated.");
            }
        } else {
            // use all default ciphers except those using RC4
            String supportedCiphers[] = sslc.getSocketFactory().getDefaultCipherSuites();
            ArrayList<String> ciphers = new ArrayList<String>(supportedCiphers.length);
            for (String cipher : supportedCiphers)
                if (!cipher.contains("_RC4_"))
                    ciphers.add(cipher);
            sortCiphers(ciphers);
            this.ciphers = ciphers.toArray(new String[ciphers.size()]);
        }
        if (setUseCipherSuitesOrderMethod == null)
            log.warn(
                    "Cannot set the cipher suite order before Java 8. This prevents Forward Secrecy with some SSL clients.");

        if (sslParser.getProtocols() != null) {
            protocols = sslParser.getProtocols().split(",");
        } else {
            protocols = null;
        }

        if (sslParser.getClientAuth() == null) {
            needClientAuth = false;
            wantClientAuth = false;
        } else if (sslParser.getClientAuth().equals("need")) {
            needClientAuth = true;
            wantClientAuth = true;
        } else if (sslParser.getClientAuth().equals("want")) {
            needClientAuth = false;
            wantClientAuth = true;
        } else {
            throw new RuntimeException("Invalid value '" + sslParser.getClientAuth()
                    + "' in clientAuth: expected 'want', 'need' or not set.");
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:de.stklcode.jvault.connector.HTTPVaultConnector.java

/**
 * Create a custom socket factory from trusted CA certificate.
 *
 * @return The factory./*w ww .ja  va2s. c o  m*/
 * @throws TlsException An error occured during initialization of the SSL context.
 * @since 0.8.0
 */
private SSLConnectionSocketFactory createSSLSocketFactory() throws TlsException {
    try {
        // Create Keystore with trusted certificate.
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setCertificateEntry("trustedCert", trustedCaCert);

        // Initialize TrustManager.
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);

        // Create context usint this TrustManager.
        SSLContext context = SSLContext.getInstance(tlsVersion);
        context.init(null, tmf.getTrustManagers(), new SecureRandom());

        return new SSLConnectionSocketFactory(context, null, null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    } catch (CertificateException | NoSuchAlgorithmException | KeyStoreException | IOException
            | KeyManagementException e) {
        throw new TlsException(Error.INIT_SSL_CONTEXT, e);
    }
}

From source file:se.leap.bitmaskclient.ProviderAPI.java

private javax.net.ssl.SSLSocketFactory getProviderSSLSocketFactory() throws KeyStoreException,
        NoSuchAlgorithmException, CertificateException, IOException, KeyManagementException {
    String provider_cert_string = preferences.getString(Provider.CA_CERT, "");

    java.security.cert.Certificate provider_certificate = ConfigHelper
            .parseX509CertificateFromString(provider_cert_string);

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, null);/* w  w w  .  j a v  a2  s  . c om*/
    keyStore.setCertificateEntry("provider_ca_certificate", provider_certificate);

    // Create a TrustManager that trusts the CAs in our KeyStore
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);

    // Create an SSLContext that uses our TrustManager
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, tmf.getTrustManagers(), null);

    return context.getSocketFactory();
}