Example usage for io.netty.handler.ssl SslContextBuilder keyManager

List of usage examples for io.netty.handler.ssl SslContextBuilder keyManager

Introduction

In this page you can find the example usage for io.netty.handler.ssl SslContextBuilder keyManager.

Prototype

public SslContextBuilder keyManager(PrivateKey key, Iterable<? extends X509Certificate> keyCertChain) 

Source Link

Document

Identifying certificate for this host.

Usage

From source file:com.datastax.driver.core.SSLTestBase.java

License:Apache License

/**
 * @param sslImplementation the SSL implementation to use
 * @param clientAuth        whether the client should authenticate
 * @param trustingServer    whether the client should trust the server's certificate
 * @return {@link com.datastax.driver.core.SSLOptions} with the given configuration for
 * server certificate validation and client certificate authentication.
 *///  w  w w . j a  v  a2 s  .  c  om
public SSLOptions getSSLOptions(SslImplementation sslImplementation, boolean clientAuth, boolean trustingServer)
        throws Exception {

    TrustManagerFactory tmf = null;
    if (trustingServer) {
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(this.getClass().getResourceAsStream(CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_PATH),
                CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_PASSWORD.toCharArray());

        tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
    }

    switch (sslImplementation) {
    case JDK:
        KeyManagerFactory kmf = null;
        if (clientAuth) {
            KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(this.getClass().getResourceAsStream(CCMBridge.DEFAULT_CLIENT_KEYSTORE_PATH),
                    CCMBridge.DEFAULT_CLIENT_KEYSTORE_PASSWORD.toCharArray());

            kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(ks, CCMBridge.DEFAULT_CLIENT_KEYSTORE_PASSWORD.toCharArray());
        }

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(kmf != null ? kmf.getKeyManagers() : null, tmf != null ? tmf.getTrustManagers() : null,
                new SecureRandom());

        return JdkSSLOptions.builder().withSSLContext(sslContext).build();

    case NETTY_OPENSSL:
        SslContextBuilder builder = SslContextBuilder.forClient().sslProvider(OPENSSL).trustManager(tmf);

        if (clientAuth) {
            builder.keyManager(CCMBridge.DEFAULT_CLIENT_CERT_CHAIN_FILE,
                    CCMBridge.DEFAULT_CLIENT_PRIVATE_KEY_FILE);
        }

        return new NettySSLOptions(builder.build());
    default:
        fail("Unsupported SSL implementation: " + sslImplementation);
        return null;
    }
}

From source file:com.yahoo.pulsar.client.impl.ConnectionPool.java

License:Apache License

public ConnectionPool(final PulsarClientImpl client, EventLoopGroup eventLoopGroup) {
    this.eventLoopGroup = eventLoopGroup;
    this.maxConnectionsPerHosts = client.getConfiguration().getConnectionsPerBroker();

    pool = new ConcurrentHashMap<>();
    bootstrap = new Bootstrap();
    bootstrap.group(eventLoopGroup);/*from  w ww .jav  a 2  s .  com*/
    if (SystemUtils.IS_OS_LINUX && eventLoopGroup instanceof EpollEventLoopGroup) {
        bootstrap.channel(EpollSocketChannel.class);
    } else {
        bootstrap.channel(NioSocketChannel.class);
    }

    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
    bootstrap.option(ChannelOption.TCP_NODELAY, client.getConfiguration().isUseTcpNoDelay());
    bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        public void initChannel(SocketChannel ch) throws Exception {
            ClientConfiguration clientConfig = client.getConfiguration();
            if (clientConfig.isUseTls()) {
                SslContextBuilder builder = SslContextBuilder.forClient();
                if (clientConfig.isTlsAllowInsecureConnection()) {
                    builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
                } else {
                    if (clientConfig.getTlsTrustCertsFilePath().isEmpty()) {
                        // Use system default
                        builder.trustManager((File) null);
                    } else {
                        File trustCertCollection = new File(clientConfig.getTlsTrustCertsFilePath());
                        builder.trustManager(trustCertCollection);
                    }
                }

                // Set client certificate if available
                AuthenticationDataProvider authData = clientConfig.getAuthentication().getAuthData();
                if (authData.hasDataForTls()) {
                    builder.keyManager(authData.getTlsPrivateKey(),
                            (X509Certificate[]) authData.getTlsCertificates());
                }

                SslContext sslCtx = builder.build();
                ch.pipeline().addLast(TLS_HANDLER, sslCtx.newHandler(ch.alloc()));
            }
            ch.pipeline().addLast("frameDecoder",
                    new PulsarLengthFieldFrameDecoder(MaxMessageSize, 0, 4, 0, 4));
            ch.pipeline().addLast("handler", new ClientCnx(client));
        }
    });
}

From source file:com.yahoo.pulsar.common.util.SecurityUtility.java

License:Apache License

public static SslContext createNettySslContext(boolean allowInsecureConnection, String trustCertsFilePath,
        Certificate[] certificates, PrivateKey privateKey)
        throws GeneralSecurityException, SSLException, FileNotFoundException {
    SslContextBuilder builder = SslContextBuilder.forClient();
    if (allowInsecureConnection) {
        builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
    } else {//from  w w w .  j av a 2s . c  om
        if (trustCertsFilePath != null && trustCertsFilePath.length() != 0) {
            builder.trustManager(new FileInputStream(trustCertsFilePath));
        }
    }
    builder.keyManager(privateKey, (X509Certificate[]) certificates);
    return builder.build();
}

From source file:com.yahoo.pulsar.discovery.service.DiscoveryServiceTest.java

License:Apache License

/**
 * creates ClientHandler channel to connect and communicate with server
 * /*from w  w w .  j a  v  a 2s. c  o m*/
 * @param serviceUrl
 * @param latch
 * @return
 * @throws URISyntaxException
 */
public static NioEventLoopGroup connectToService(String serviceUrl, CountDownLatch latch, boolean tls)
        throws URISyntaxException {
    NioEventLoopGroup workerGroup = new NioEventLoopGroup();
    Bootstrap b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);

    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            if (tls) {
                SslContextBuilder builder = SslContextBuilder.forClient();
                builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
                X509Certificate[] certificates = SecurityUtility
                        .loadCertificatesFromPemFile(TLS_CLIENT_CERT_FILE_PATH);
                PrivateKey privateKey = SecurityUtility.loadPrivateKeyFromPemFile(TLS_CLIENT_KEY_FILE_PATH);
                builder.keyManager(privateKey, (X509Certificate[]) certificates);
                SslContext sslCtx = builder.build();
                ch.pipeline().addLast("tls", sslCtx.newHandler(ch.alloc()));
            }
            ch.pipeline().addLast(new ClientHandler(latch));
        }
    });
    URI uri = new URI(serviceUrl);
    InetSocketAddress serviceAddress = new InetSocketAddress(uri.getHost(), uri.getPort());
    b.connect(serviceAddress).addListener((ChannelFuture future) -> {
        if (!future.isSuccess()) {
            throw new IllegalStateException(future.cause());
        }
    });
    return workerGroup;
}

From source file:io.grpc.examples.helloworldtls.HelloWorldClientTls.java

License:Apache License

private static SslContext buildSslContext(String trustCertCollectionFilePath, String clientCertChainFilePath,
        String clientPrivateKeyFilePath) throws SSLException {
    SslContextBuilder builder = GrpcSslContexts.forClient();
    if (trustCertCollectionFilePath != null) {
        builder.trustManager(new File(trustCertCollectionFilePath));
    }//from  www. jav a 2  s.co m
    if (clientCertChainFilePath != null && clientPrivateKeyFilePath != null) {
        builder.keyManager(new File(clientCertChainFilePath), new File(clientPrivateKeyFilePath));
    }
    return builder.build();
}

From source file:net.devh.boot.grpc.client.channelfactory.NettyChannelFactory.java

License:Open Source License

@Override
// Keep this in sync with ShadedNettyChannelFactory#configureSecurity
protected void configureSecurity(final NettyChannelBuilder builder, final String name) {
    final GrpcChannelProperties properties = getPropertiesFor(name);

    final NegotiationType negotiationType = properties.getNegotiationType();
    builder.negotiationType(of(negotiationType));

    if (negotiationType == NegotiationType.TLS) {
        final Security security = properties.getSecurity();

        final String authorityOverwrite = security.getAuthorityOverride();
        if (authorityOverwrite != null && !authorityOverwrite.isEmpty()) {
            builder.overrideAuthority(authorityOverwrite);
        }/* w  w  w  .  j  a  va2s . com*/

        final SslContextBuilder sslContextBuilder = GrpcSslContexts.forClient();

        if (security.isClientAuthEnabled()) {
            final File keyCertChainFile = toCheckedFile("keyCertChain", security.getCertificateChainPath());
            final File privateKeyFile = toCheckedFile("privateKey", security.getPrivateKeyPath());
            sslContextBuilder.keyManager(keyCertChainFile, privateKeyFile);
        }

        final String trustCertCollectionPath = security.getTrustCertCollectionPath();
        if (trustCertCollectionPath != null && !trustCertCollectionPath.isEmpty()) {
            final File trustCertCollectionFile = toCheckedFile("trustCertCollection", trustCertCollectionPath);
            sslContextBuilder.trustManager(trustCertCollectionFile);
        }

        try {
            builder.sslContext(sslContextBuilder.build());
        } catch (final SSLException e) {
            throw new IllegalStateException("Failed to create ssl context for grpc client", e);
        }
    }
}

From source file:org.hyperledger.fabric.sdk.security.TLSCertGenTest.java

License:Open Source License

private SslContextBuilder getSslContextBuilder(File clientCertFile, File clientKeyFile, File serverCertFile) {
    SslProvider sslprovider = SslProvider.OPENSSL;
    SslContextBuilder ctxBuilder = SslContextBuilder.forClient().protocols(TLS_PROTOCOL)
            .trustManager(serverCertFile);
    SslContextBuilder clientContextBuilder = GrpcSslContexts.configure(ctxBuilder, sslprovider);
    clientContextBuilder = clientContextBuilder.keyManager(clientCertFile, clientKeyFile);
    return clientContextBuilder;
}