Example usage for javax.net.ssl TrustManagerFactory getInstance

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

Introduction

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

Prototype

public static final TrustManagerFactory getInstance(String algorithm, Provider provider)
        throws NoSuchAlgorithmException 

Source Link

Document

Returns a TrustManagerFactory object that acts as a factory for trust managers.

Usage

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

@OnScheduled
public void startServer(final ProcessContext context) throws NoSuchAlgorithmException, IOException,
        KeyStoreException, CertificateException, UnrecoverableKeyException {
    final ComponentLog logger = getLogger();
    // gather configured properties
    final Integer port = context.getProperty(PROP_SERVICE_PORT).asInteger();
    final Boolean useSecure = context.getProperty(PROP_USE_SECURE).asBoolean();
    final Integer flowControlWindow = context.getProperty(PROP_FLOW_CONTROL_WINDOW).asDataSize(DataUnit.B)
            .intValue();//from w ww.java  2s .  c om
    final Integer maxMessageSize = context.getProperty(PROP_MAX_MESSAGE_SIZE).asDataSize(DataUnit.B).intValue();
    final SSLContextService sslContextService = context.getProperty(PROP_SSL_CONTEXT_SERVICE)
            .asControllerService(SSLContextService.class);
    final SSLContext sslContext = sslContextService == null ? null
            : sslContextService.createSSLContext(SSLContextService.ClientAuth.NONE);
    final Pattern authorizedDnPattern = Pattern
            .compile(context.getProperty(PROP_AUTHORIZED_DN_PATTERN).getValue());
    final FlowFileIngestServiceInterceptor callInterceptor = new FlowFileIngestServiceInterceptor(getLogger());
    callInterceptor.enforceDNPattern(authorizedDnPattern);

    final FlowFileIngestService flowFileIngestService = new FlowFileIngestService(getLogger(),
            sessionFactoryReference, context);
    NettyServerBuilder serverBuilder = NettyServerBuilder.forPort(port)
            .addService(ServerInterceptors.intercept(flowFileIngestService, callInterceptor))
            // default (de)compressor registries handle both plaintext and gzip compressed messages
            .compressorRegistry(CompressorRegistry.getDefaultInstance())
            .decompressorRegistry(DecompressorRegistry.getDefaultInstance())
            .flowControlWindow(flowControlWindow).maxMessageSize(maxMessageSize);

    if (useSecure && sslContext != null) {
        // construct key manager
        if (StringUtils.isBlank(sslContextService.getKeyStoreFile())) {
            throw new IllegalStateException(
                    "SSL is enabled, but no keystore has been configured. You must configure a keystore.");
        }

        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 sslContextBuilder = SslContextBuilder.forServer(keyManagerFactory);

        // if the trust store is configured, then client auth is required.
        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 = sslContextBuilder.trustManager(trustManagerFactory);
            sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.REQUIRE);
        } else {
            sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.NONE);
        }
        sslContextBuilder = GrpcSslContexts.configure(sslContextBuilder);
        serverBuilder = serverBuilder.sslContext(sslContextBuilder.build());
    }
    logger.info("Starting gRPC server on port: {}", new Object[] { port.toString() });
    this.server = serverBuilder.build().start();
}

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  w w.j  av a2  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.beepcore.beep.profile.tls.jsse.TLSProfileJSSE.java

/**
 * init sets the criteria for which an SSL connection is made when
 * a TLS channel is started for a profile.  It should only be
 * called once.  For the properties, the initiator is defined as
 * the peer who starts the channel for the TLS profile, the
 * listener is the peer that receives the the channel start
 * request, irregardless of which actually started the session.<p>
 *
 * @param config <code>ProfileConfiguration</code> object that
 * contains key value pairs to initialize the TLS layer.  None of
 * these are mandatory, but if you wish communication to be
 * anonymous with no authentication, (i.e., the listener to not
 * send back a certificate), you must set "Listener Anonymous" to
 * "true" and "Initiator Authentication Required" to "false".
 * The meaningful properties that can be set are these:<p>
 * <table>//from  w w  w  .j  a  va 2 s  . c  om
 * <tr>
 * <td>Listener Anonymous</td><td>(true|false) must be set to false if the
 *   listener will not authenticate itself</td>
 * </tr><tr>
 * <td>Initiator Authentication Required</td><td>(true|false) set if the
 *       initiator should send a certificate and the listener expects a
 *       certificate.</td>
 * </tr><tr>
 * <td>Cipher Suite</td><td><i>not yet implemented.</i>the algorithms that
 *       can be used for encryption, authentication, and key exchange.</td>
 * </tr><tr>
 * <td>Key Algorithm</td><td>key management algorithm. See
 *       {@link com.sun.net.ssl.KeyManagerFactory#getInstance}</td>
 * </tr><tr>
 * <td>Key Provider</td><td>provider of the key management
 *       algorithm.  Defaults to
 *    <code>com.sun.net.ssl.internal.ssl.Provider</code> See
 *       {@link com.sun.net.ssl.KeyManagerFactory#getInstance}</td>
 * </tr><tr>
 * <td>Trust Algorithm</td><td>algorithm to be used by the trust
 *       manager.  See
 *       {@link com.sun.net.ssl.TrustManagerFactory#getInstance}</td>
 * </tr><tr>
 * <td>Trust Provider</td><td>provider of the trust manager.  Defaults to
 *    <code>com.sun.net.ssl.internal.ssl.Provider</code>.  See
 *    {@link com.sun.net.ssl.TrustManagerFactory#getInstance}</td>
 * </tr><tr>
 * <td>Key Store Passphrase</td><td>pass phrase used to encrypt the key
 *    store.  See {@link java.security.KeyStore#load}</td>
 * </tr><tr>
 * <td>Key Store Data Type</td><td>data type of the key store passed in.
 *     "file" is currently the only value accepted, meaning Key Store
 *     is the name of a file containing keys.  See
 *     {@link java.security.KeyStore#load}</td>
 * </tr><tr>
 * <td>Key Store</td><td>value of the key store, dependent on the type in
 *     Key Store Data Type.  See {@link java.security.KeyStore#load}</td>
 * </tr><tr>
 * <td>Key Store Format</td><td>format of the keys within the key store.
 *  Default is "JKS".  See {@link java.security.KeyStore#getInstance}</td>
 * </tr><tr>
 * <td>Key Store Provider</td><td>provider for the key stores.  See
 *     {@link java.security.KeyStore#getInstance}</td>
 * </tr><tr>
 * <td>Trust Store Passphrase</td><td>pass phrase used to encrypt the trust
 *     store.  See {@link java.security.KeyStore#load}</td>
 * </tr><tr>
 * <td>Trust Store Data Type</td><td>data type of the certificates in the
 * trust store.  "file" is currently th only value accepted,
 * meaning the trust store is a file on the local disk.  See
 *     {@link java.security.KeyStore#load}</td>
 * </tr><tr>
 * <td>Trust Store</td><td>value of the trust store, dependent on the type
 *     in Trust
 *     Store Data Type  See {@link java.security.KeyStore#load}</td>
 * </tr><tr>
 * <td>Trust Store Format</td><td>format of the certificates within the
 *     trust store.
 * Default is "JKS".  See {@link java.security.KeyStore#getInstance}</td>
 * </tr><tr>
 * <td>Trust Store Provider</td><td>provider for the trust stores.  See
 *     {@link java.security.KeyStore#getInstance}</td>
 * </tr><tr>
 * <td>Allowed SSL Protocols</td><td>Comma separated list of algorithms 
 * that may be used for SSL/TLS negotiations. By default, this will be 
 * whatever the {@link SSLSocket} implementation supports.
 * @see SSLSocket#getSupportedProtocols()
 * @see SSLSocket#setEnabledProtocols(String[])
 * </tr><tr>
 * </table>
 * @throws BEEPException For any error in the profile configuration, a
 * negative response in the form of a BEEP error will be sent back to the
 * requesting peer.  The session will continue to be open and usable, at
 * least from the standpoint of this peer.
 *
 * @see com.sun.net.ssl.KeyManagerFactory
 * @see com.sun.net.ssl.TrustManagerFactory
 * @see java.security.KeyStore
 * @see com.sun.net.ssl.SSLContext
 */
public StartChannelListener init(String uri, ProfileConfiguration config) throws BEEPException {
    KeyManagerFactory kmf = null;
    KeyManager[] km = null;
    KeyStore ks = null;
    TrustManagerFactory tmf = null;
    TrustManager[] tm = null;
    KeyStore ts = null;
    SSLContext ctx;
    this.sslProtocols = null;

    // set the URI of this instance of the profile
    this.uri = uri;

    try {

        // create an SSL context object
        ctx = SSLContext.getInstance("TLS");
    } catch (java.security.NoSuchAlgorithmException e) {
        throw new BEEPException("TLS Algorithm Not Found. Probable " + "cause is the JSSE provider has not "
                + "been added to the java.security file.");
    }

    try {
        String protocols = config.getProperty(PROPERTY_SSL_PROTOCOLS);
        if (protocols != null) {
            this.sslProtocols = protocols.split(",");
        }
        // initialize the key managers, trust managers, and
        keyAlgorithm = config.getProperty(PROPERTY_KEY_MANAGER_ALGORITHM);
        keyProvider = config.getProperty(PROPERTY_KEY_MANAGER_PROVIDER);
        trustAlgorithm = config.getProperty(PROPERTY_TRUST_MANAGER_ALGORITHM);
        trustProvider = config.getProperty(PROPERTY_TRUST_MANAGER_PROVIDER);
        keyPassphrase = config.getProperty(PROPERTY_KEYSTORE_PASSPHRASE);
        keyStoreType = config.getProperty(PROPERTY_KEYSTORE_TYPE);
        keyStoreName = config.getProperty(PROPERTY_KEYSTORE_NAME);
        keyStoreFormat = config.getProperty(PROPERTY_KEYSTORE_FORMAT, "JKS");
        keyStoreProvider = config.getProperty(PROPERTY_KEYSTORE_PROVIDER);
        trustPassphrase = config.getProperty(PROPERTY_TRUSTSTORE_PASSPHRASE);
        trustStoreType = config.getProperty(PROPERTY_TRUSTSTORE_TYPE);
        trustStoreName = config.getProperty(PROPERTY_TRUSTSTORE_NAME);
        trustStoreFormat = config.getProperty(PROPERTY_TRUSTSTORE_FORMAT, "JKS");
        trustStoreProvider = config.getProperty(PROPERTY_TRUSTSTORE_PROVIDER);

        // determine if the client must authenticate or if the server can
        // 
        needClientAuth = new Boolean(config.getProperty(PROPERTY_CLIENT_AUTHENTICATION, "false"))
                .booleanValue();
        serverAnonymous = new Boolean(config.getProperty(PROPERTY_SERVER_ANONYMOUS, "true")).booleanValue();

        if (keyAlgorithm != null) {
            if (keyProvider != null) {
                kmf = KeyManagerFactory.getInstance(keyAlgorithm, keyProvider);
            } else {
                kmf = KeyManagerFactory.getInstance(keyAlgorithm);
            }

            // add support for a default type of key manager factory?
            if (keyStoreProvider != null) {
                ks = KeyStore.getInstance(keyStoreFormat, keyStoreProvider);
            } else {
                ks = KeyStore.getInstance(keyStoreFormat);
            }

            if (keyStoreType.equals("file")) {
                ks.load(new FileInputStream(keyStoreName), keyPassphrase.toCharArray());
            } else {
                throw new BEEPException(ERR_ILLEGAL_KEY_STORE);
            }

            // initialize the key factory manager 
            kmf.init(ks, keyPassphrase.toCharArray());

            km = kmf.getKeyManagers();
        } else {
            km = null;
        }

        if (trustAlgorithm != null) {
            if (trustProvider != null) {
                tmf = TrustManagerFactory.getInstance(trustAlgorithm, trustProvider);
            } else {
                tmf = TrustManagerFactory.getInstance(trustAlgorithm);
            }

            // add support for a default type of trust manager factory?
            if (trustStoreProvider != null) {
                ts = KeyStore.getInstance(trustStoreFormat, trustStoreProvider);
            } else {
                ts = KeyStore.getInstance(trustStoreFormat);
            }

            if (trustStoreType.equals("file")) {
                ts.load(new FileInputStream(trustStoreName), trustPassphrase.toCharArray());
            } else {
                throw new BEEPException(ERR_ILLEGAL_TRUST_STORE);
            }

            // initialize the trust factory manager 
            tmf.init(ts);

            tm = tmf.getTrustManagers();
        } else {
            tm = null;
        }

        // create a socket factory from the key factories and
        // trust factories created for the algorithms and stores
        // specfied.  No option is given to change the secure
        // random number generator
        ctx.init(km, tm, null);

        socketFactory = ctx.getSocketFactory();

        return this;
    } catch (Exception e) {
        log.error(e);

        throw new BEEPException(e);
    }
}