Example usage for javax.net.ssl SSLContext getProvider

List of usage examples for javax.net.ssl SSLContext getProvider

Introduction

In this page you can find the example usage for javax.net.ssl SSLContext getProvider.

Prototype

public final Provider getProvider() 

Source Link

Document

Returns the provider of this SSLContext object.

Usage

From source file:be.fedict.eid.idp.sp.protocol.saml2.artifact.ArtifactServiceClient.java

/**
 * If set, unilateral TLS authentication will occur, verifying the server
 * {@link X509Certificate} specified against the {@link PublicKey}.
 * //from   w  w w.  j a  v  a 2  s. c o  m
 * @param publicKey
 *            public key to validate server TLS certificate against.
 */
public void setServicePublicKey(final PublicKey publicKey) {

    // Create TrustManager
    TrustManager[] trustManager = { new X509TrustManager() {

        public X509Certificate[] getAcceptedIssuers() {

            return null;
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            X509Certificate serverCertificate = chain[0];
            LOG.debug("server X509 subject: " + serverCertificate.getSubjectX500Principal().toString());
            LOG.debug("authentication type: " + authType);
            if (null == publicKey) {
                return;
            }

            try {
                serverCertificate.verify(publicKey);
                LOG.debug("valid server certificate");
            } catch (InvalidKeyException e) {
                throw new CertificateException("Invalid Key");
            } catch (NoSuchAlgorithmException e) {
                throw new CertificateException("No such algorithm");
            } catch (NoSuchProviderException e) {
                throw new CertificateException("No such provider");
            } catch (SignatureException e) {
                throw new CertificateException("Wrong signature");
            }
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            throw new CertificateException("this trust manager cannot be used as server-side trust manager");
        }
    } };

    // Create SSL Context
    try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        SecureRandom secureRandom = new SecureRandom();
        sslContext.init(null, trustManager, secureRandom);
        LOG.debug("SSL context provider: " + sslContext.getProvider().getName());

        // Setup TrustManager for validation
        Map<String, Object> requestContext = ((BindingProvider) this.port).getRequestContext();
        requestContext.put(JAXWSProperties.SSL_SOCKET_FACTORY, sslContext.getSocketFactory());

    } catch (KeyManagementException e) {
        String msg = "key management error: " + e.getMessage();
        LOG.error(msg, e);
        throw new RuntimeException(msg, e);
    } catch (NoSuchAlgorithmException e) {
        String msg = "TLS algo not present: " + e.getMessage();
        LOG.error(msg, e);
        throw new RuntimeException(msg, e);
    }
}

From source file:be.fedict.trust.client.XKMS2Client.java

/**
 * If set, unilateral TLS authentication will occurs, verifying the server
 * {@link X509Certificate} specified {@link PublicKey}.
 * <p/>/* w w  w  .  j  av  a  2 s  . c  om*/
 * WARNING: only works when using the JAX-WS RI.
 * 
 * @param publicKey
 *            public key to validate server TLS certificate against.
 */
public void setServicePublicKey(final PublicKey publicKey) {
    // Create TrustManager
    TrustManager[] trustManager = { new X509TrustManager() {

        public X509Certificate[] getAcceptedIssuers() {

            return null;
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            X509Certificate serverCertificate = chain[0];
            LOG.debug("server X509 subject: " + serverCertificate.getSubjectX500Principal().toString());
            LOG.debug("authentication type: " + authType);
            if (null == publicKey) {
                LOG.warn("not performing any server certificate validation at all");
                return;
            }

            try {
                serverCertificate.verify(publicKey);
                LOG.debug("valid server certificate");
            } catch (InvalidKeyException e) {
                throw new CertificateException("Invalid Key");
            } catch (NoSuchAlgorithmException e) {
                throw new CertificateException("No such algorithm");
            } catch (NoSuchProviderException e) {
                throw new CertificateException("No such provider");
            } catch (SignatureException e) {
                throw new CertificateException("Wrong signature");
            }
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            throw new CertificateException("this trust manager cannot be used as server-side trust manager");
        }
    } };

    // Create SSL Context
    try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        SecureRandom secureRandom = new SecureRandom();
        sslContext.init(null, trustManager, secureRandom);
        LOG.debug("SSL context provider: " + sslContext.getProvider().getName());

        // Setup TrustManager for validation
        Map<String, Object> requestContext = ((BindingProvider) this.port).getRequestContext();
        requestContext.put("com.sun.xml.ws.transport.https.client.SSLSocketFactory",
                sslContext.getSocketFactory());

    } catch (KeyManagementException e) {
        String msg = "key management error: " + e.getMessage();
        LOG.error(msg, e);
        throw new RuntimeException(msg, e);
    } catch (NoSuchAlgorithmException e) {
        String msg = "TLS algo not present: " + e.getMessage();
        LOG.error(msg, e);
        throw new RuntimeException(msg, e);
    }
}

From source file:net.timewalker.ffmq4.listeners.tcp.io.TcpListener.java

private SSLContext createSSLContext() throws JMSException {
    try {/*from  w  w  w. j ava2s.  c  om*/
        String sslProtocol = settings.getStringProperty(FFMQCoreSettings.TRANSPORT_TCP_SSL_PROTOCOL, "SSLv3");
        String keyManagerAlgorithm = settings
                .getStringProperty(FFMQCoreSettings.TRANSPORT_TCP_SSL_KEYMANAGER_ALGORITHM, "SunX509");
        String keyStoreType = settings.getStringProperty(FFMQCoreSettings.TRANSPORT_TCP_SSL_KEYSTORE_TYPE,
                "JKS");
        String keyStorePath = settings.getStringProperty(FFMQCoreSettings.TRANSPORT_TCP_SSL_KEYSTORE_PATH,
                "../conf/server-keystore.jks");
        String keyStorePass = settings.getStringProperty(FFMQCoreSettings.TRANSPORT_TCP_SSL_KEYSTORE_PASWORD,
                "ffmqpass");
        String keyPass = settings.getStringProperty(FFMQCoreSettings.TRANSPORT_TCP_SSL_KEYSTORE_KEY_PASSWORD,
                "ffmqpass");

        SSLContext sslContext = SSLContext.getInstance(sslProtocol);
        log.debug("Created an SSL context : protocol=[" + sslContext.getProtocol() + "] provider=["
                + sslContext.getProvider() + "]");

        // Load available keys
        KeyManager[] keyManagers;
        File keyStoreFile = new File(keyStorePath);
        if (!keyStoreFile.canRead())
            throw new FFMQException("Cannot read keystore file : " + keyStoreFile.getAbsolutePath(),
                    "FS_ERROR");

        KeyStore ks = KeyStore.getInstance(keyStoreType);
        log.debug("Created keystore : type=[" + ks.getType() + "] provider=[" + ks.getProvider() + "]");
        char ksPass[] = keyStorePass.toCharArray();
        char ctPass[] = keyPass.toCharArray();
        log.debug("Loading keystore from " + keyStoreFile.getAbsolutePath());
        InputStream kis = new FileInputStream(keyStoreFile);
        ks.load(kis, ksPass);
        kis.close();

        KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManagerAlgorithm);
        log.debug("Created KeyManagerFactory : algorithm=[" + kmf.getAlgorithm() + "] provider=["
                + kmf.getProvider() + "]");
        log.debug("Initializing KeyManagerFactory with keystore ...");
        kmf.init(ks, ctPass);

        keyManagers = kmf.getKeyManagers();

        sslContext.init(keyManagers, null, null);

        return sslContext;
    } catch (JMSException e) {
        throw e;
    } catch (Exception e) {
        throw new FFMQException("Cannot create SSL context", "NETWORK_ERROR", e);
    }
}

From source file:net.timewalker.ffmq4.transport.tcp.io.TcpPacketTransport.java

private SSLContext createSSLContext() throws JMSException {
    try {//from  w  w  w.ja v  a  2s  .  com
        String sslProtocol = settings.getStringProperty(FFMQClientSettings.TRANSPORT_TCP_SSL_PROTOCOL, "SSLv3");
        boolean ignoreCertificates = settings
                .getBooleanProperty(FFMQClientSettings.TRANSPORT_TCP_SSL_IGNORE_CERTS, false);

        SSLContext sslContext = SSLContext.getInstance(sslProtocol);
        log.debug("#" + id + " created an SSL context : protocol=[" + sslContext.getProtocol() + "] provider=["
                + sslContext.getProvider() + "]");

        // Load available keys
        KeyManager[] keyManagers = null;
        TrustManager[] trustManagers = null;

        if (ignoreCertificates)
            trustManagers = new TrustManager[] { new PermissiveTrustManager() };

        sslContext.init(keyManagers, trustManagers, null);

        return sslContext;
    } catch (Exception e) {
        throw new FFMQException("Cannot create SSL context", "TRANSPORT_ERROR", e);
    }
}

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.//from   w  ww.jav a2s.co 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.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();//  w w  w.j a  va 2 s  . c  o  m
    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.syncany.operations.gui.GuiWebSocketClient.java

private void connect(final DaemonConfigTO daemonConfig, final UserTO daemonUser) throws Exception {
    logger.log(Level.INFO, "Starting GUI websocket client with user " + daemonUser.getUsername() + " at "
            + daemonConfig.getWebServer().getBindAddress() + " ...");

    SSLContext sslContext = UserConfig.createUserSSLContext();
    Xnio xnio = Xnio.getInstance(this.getClass().getClassLoader());
    Pool<ByteBuffer> buffer = new ByteBufferSlicePool(BufferAllocator.BYTE_BUFFER_ALLOCATOR, 1024, 1024);

    OptionMap workerOptions = OptionMap.builder().set(Options.WORKER_IO_THREADS, 2)
            .set(Options.WORKER_TASK_CORE_THREADS, 30).set(Options.WORKER_TASK_MAX_THREADS, 30)
            .set(Options.SSL_PROTOCOL, sslContext.getProtocol())
            .set(Options.SSL_PROVIDER, sslContext.getProvider().getName()).set(Options.TCP_NODELAY, true)
            .set(Options.CORK, true).getMap();

    XnioWorker worker = xnio.createWorker(workerOptions);
    XnioSsl xnioSsl = new JsseXnioSsl(xnio, OptionMap.create(Options.USE_DIRECT_BUFFERS, true), sslContext);
    URI uri = new URI(PROTOCOL + daemonConfig.getWebServer().getBindAddress() + ":"
            + daemonConfig.getWebServer().getBindPort() + ENDPOINT);

    WebSocketClientNegotiation clientNegotiation = new WebSocketClientNegotiation(new ArrayList<String>(),
            new ArrayList<WebSocketExtension>()) {
        @Override/*from  w ww  .  j  av a2  s . co  m*/
        public void beforeRequest(Map<String, String> headers) {
            String basicAuthPlainUserPass = daemonUser.getUsername() + ":" + daemonUser.getPassword();
            String basicAuthEncodedUserPass = Base64
                    .encodeBase64String(StringUtil.toBytesUTF8(basicAuthPlainUserPass));

            headers.put("Authorization", "Basic " + basicAuthEncodedUserPass);
        }
    };

    webSocketChannel = WebSocketClient
            .connect(worker, xnioSsl, buffer, workerOptions, uri, WebSocketVersion.V13, clientNegotiation)
            .get();

    webSocketChannel.getReceiveSetter().set(new AbstractReceiveListener() {
        @Override
        protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage textMessage)
                throws IOException {
            String messageStr = textMessage.getData();
            Message message;

            try {
                logger.log(Level.INFO, "GUI received message: " + messageStr);

                message = MessageFactory.toMessage(messageStr);
                eventBus.post(message);
            } catch (Exception e) {
                logger.log(Level.WARNING, "Unable to parse message: " + e);
            }
        }

        @Override
        protected void onError(WebSocketChannel channel, Throwable error) {
            logger.log(Level.WARNING, "Error: " + error.getMessage());
            waitAndReconnect();
        }
    });

    webSocketChannel.resumeReceives();
}

From source file:test.integ.be.fedict.trust.util.SSLTrustManager.java

private static void initSocketFactory() {

    LOG.debug("init socket factory");
    SSLTrustManager trustManagerInstance = new SSLTrustManager();
    TrustManager[] trustManager = { trustManagerInstance };
    try {/*from  w w w . ja va2 s.  c o  m*/
        SSLContext sslContext = SSLContext.getInstance("TLS");
        SecureRandom secureRandom = new SecureRandom();
        sslContext.init(null, trustManager, secureRandom);
        LOG.debug("SSL context provider: " + sslContext.getProvider().getName());
        socketFactory = sslContext.getSocketFactory();
    } catch (KeyManagementException e) {
        String msg = "key management error: " + e.getMessage();
        LOG.error(msg, e);
        throw new RuntimeException(msg, e);
    } catch (NoSuchAlgorithmException e) {
        String msg = "TLS algo not present: " + e.getMessage();
        LOG.error(msg, e);
        throw new RuntimeException(msg, e);
    }
}