List of usage examples for javax.net.ssl KeyManagerFactory init
public final void init(KeyStore ks, char[] password) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException
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 www . ja v a 2 s. co 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:it.jnrpe.server.CBindingThread.java
/** * Returns the SSL factory to be used to create the Server Socket * @throws KeyStoreException // w w w . j ava 2s .c om * @throws IOException * @throws FileNotFoundException * @throws CertificateException * @throws UnrecoverableKeyException * @throws KeyManagementException * * @see it.intesa.fi2.client.network.ISSLObjectsFactory#getSSLSocketFactory(String, String, String) */ public SSLServerSocketFactory getSSLSocketFactory(String sKeyStoreFile, String sKeyStorePwd, String sKeyStoreType) throws KeyStoreException, CertificateException, FileNotFoundException, IOException, UnrecoverableKeyException, KeyManagementException { if (sKeyStoreFile == null) throw new KeyStoreException("KEYSTORE HAS NOT BEEN SPECIFIED"); if (this.getClass().getClassLoader().getResourceAsStream(sKeyStoreFile) == null) throw new KeyStoreException("COULD NOT FIND KEYSTORE '" + sKeyStoreFile + "'"); if (sKeyStorePwd == null) throw new KeyStoreException("KEYSTORE PASSWORD HAS NOT BEEN SPECIFIED"); SSLContext ctx; KeyManagerFactory kmf; try { ctx = SSLContext.getInstance("SSLv3"); kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); //KeyStore ks = getKeystore(sKeyStoreFile, sKeyStorePwd, sKeyStoreType); KeyStore ks = KeyStore.getInstance(sKeyStoreType); ks.load(this.getClass().getClassLoader().getResourceAsStream(sKeyStoreFile), sKeyStorePwd.toCharArray()); char[] passphrase = sKeyStorePwd.toCharArray(); kmf.init(ks, passphrase); ctx.init(kmf.getKeyManagers(), null, new java.security.SecureRandom()); } catch (NoSuchAlgorithmException e) { throw new SSLException("Unable to initialize SSLSocketFactory.\n" + e.getMessage()); } return ctx.getServerSocketFactory(); }
From source file:org.sandrob.android.net.http.HttpsConnection.java
/** * /* w w w . j av a 2s .co m*/ * * @param sessionDir directory to cache SSL sessions * @param req request that call this function */ public void initializeEngine(File sessionDir, Request req) { if (mSslSocketFactory == null) { String certificateFullPathName = null; String keyStoreType = "PKCS12"; String keyStoreProvider = "BC"; String certificatePassword = null; try { SSLClientSessionCache cache = null; KeyManager[] keyManagers = null; KeyStore keyStore = null; if (sessionDir != null) { Log.d("HttpsConnection", "Caching SSL sessions in " + sessionDir + "."); cache = FileClientSessionCache.usingDirectory(sessionDir); } // Inform the user if we need ssl client settings if (true) { synchronized (mSuspendLock) { mSuspended = true; } // don't hold the lock while calling out to the event handler boolean canHandle = req.getEventHandler().handleSslClientSetingsRequest(); if (!canHandle) { throw new IOException("failed to handle ssl client settings "); } synchronized (mSuspendLock) { if (mSuspended) { try { // Put a limit on how long we are waiting; if the timeout // expires (which should never happen unless you choose // to ignore the SSL error dialog for a very long time), // we wake up the thread and abort the request. This is // to prevent us from stalling the network if things go // very bad. mSuspendLock.wait(10 * 60 * 1000); if (mSuspended) { // mSuspended is true if we have not had a chance to // restart the connection yet (ie, the wait timeout // has expired) mSuspended = false; mAborted = true; if (HttpLog.LOGV) { HttpLog.v("HttpsConnection.openConnection():" + " SSL timeout expired and request was cancelled!!!"); } } } catch (InterruptedException e) { // ignore } } if (mAborted) { // The user decided not to use this unverified connection // so close it immediately. throw new SSLConnectionClosedByUserException("connection closed by the user"); } if (mSslClientCertificate != null) { // we have some data about client certificate certificateFullPathName = mSslClientCertificate.getCertificateFileName(); certificatePassword = mSslClientCertificate.getCertificateFilePassword(); } } } SSLContextImpl sslContext = new SSLContextImpl(); //SSLContext sslContext = SSLContext.getInstance("TLS"); if (certificateFullPathName != null && certificatePassword != null) { File certFile = new File(certificateFullPathName); if (certFile.exists()) { keyStore = KeyStore.getInstance(keyStoreType, keyStoreProvider); keyStore.load(new FileInputStream(new File(certificateFullPathName)), certificatePassword.toCharArray()); String kmfa = KeyManagerFactory.getDefaultAlgorithm(); KeyManagerFactory kmf = KeyManagerFactory.getInstance(kmfa); kmf.init(keyStore, certificatePassword.toCharArray()); keyManagers = kmf.getKeyManagers(); } } // here, trust managers is a single trust-all manager TrustManager[] trustManagers = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; sslContext.engineInit(keyManagers, trustManagers, null, cache, null); //sslContext.init(keyManagers, trustManagers, null); synchronized (HttpsConnection.class) { mSslSocketFactory = sslContext.engineGetSocketFactory(); //mSslSocketFactory = sslContext.getSocketFactory(); } } catch (KeyManagementException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } } }
From source file:org.wildfly.security.sasl.entity.EntityTest.java
private X509KeyManager getX509KeyManager(final File keyStore, final char[] keyStorePassword) throws GeneralSecurityException, IOException { KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(loadKeyStore(keyStore), keyStorePassword); for (KeyManager keyManager : keyManagerFactory.getKeyManagers()) { if (keyManager instanceof X509KeyManager) { return (X509KeyManager) keyManager; }//from ww w .j ava 2 s .c o m } return null; }
From source file:org.opennms.netmgt.provision.server.SSLServer.java
/** * <p>init</p>//from w ww. j ava 2s . c o m * * @throws java.lang.Exception if any. */ @Override public void init() throws Exception { super.init(); KeyManagerFactory kmf = KeyManagerFactory.getInstance(getKeyManagerAlgorithm(), getKeyManagerProvider()); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); char[] password = getPassword().toCharArray(); java.io.FileInputStream fis = null; try { fis = new java.io.FileInputStream(getPathToKeyStore()); ks.load(fis, password); } finally { if (fis != null) { fis.close(); } } kmf.init(ks, password); KeyManager[] km = kmf.getKeyManagers(); SSLContext sslContext = SSLContext.getInstance(getSslContextProtocol()); sslContext.init(km, null, new SecureRandom()); SSLServerSocketFactory serverFactory = sslContext.getServerSocketFactory(); setServerSocket(serverFactory.createServerSocket(getPort())); onInit(); }
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 ww.j ava2 s.co 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.sonatype.nexus.ssl.plugin.internal.TrustStoreImpl.java
private static KeyManager[] getSystemKeyManagers() throws Exception { KeyManagerFactory keyManagerFactory; String keyAlgorithm = System.getProperty("ssl.KeyManagerFactory.algorithm"); if (keyAlgorithm == null) { keyAlgorithm = KeyManagerFactory.getDefaultAlgorithm(); }/*w ww .j ava 2s . c o m*/ String keyStoreType = System.getProperty("javax.net.ssl.keyStoreType"); if (keyStoreType == null) { keyStoreType = KeyStore.getDefaultType(); } if ("none".equalsIgnoreCase(keyStoreType)) { keyManagerFactory = KeyManagerFactory.getInstance(keyAlgorithm); } else { final String keyStoreFileName = System.getProperty("javax.net.ssl.keyStore"); if (keyStoreFileName != null) { File keyStoreFile = new File(keyStoreFileName); keyManagerFactory = KeyManagerFactory.getInstance(keyAlgorithm); String keyStoreProvider = System.getProperty("javax.net.ssl.keyStoreProvider"); KeyStore keyStore; if (keyStoreProvider != null) { keyStore = KeyStore.getInstance(keyStoreType, keyStoreProvider); } else { keyStore = KeyStore.getInstance(keyStoreType); } String password = System.getProperty("javax.net.ssl.keyStorePassword"); try (FileInputStream in = new FileInputStream(keyStoreFile)) { keyStore.load(in, password != null ? password.toCharArray() : null); } keyManagerFactory.init(keyStore, password != null ? password.toCharArray() : null); } else { return null; } } return keyManagerFactory.getKeyManagers(); }
From source file:mitm.common.security.ca.handlers.ejbca.EJBCACertificateRequestHandler.java
private EjbcaWS getEjbcaWS() throws CAException { if (ejbcaWS == null) { try {//from w ww. j av a 2s. co m JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); factory.setServiceClass(EjbcaWS.class); factory.setAddress(requestHandlerSettings.getWebServiceURL().toExternalForm()); factory.setServiceName(EJBCAConst.SERVICE_NAME); EjbcaWS localEjbcaWS = (EjbcaWS) factory.create(); KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); char[] password = requestHandlerSettings.getKeyStorePassword() != null ? requestHandlerSettings.getKeyStorePassword().toCharArray() : null; keyManagerFactory.init(requestHandlerSettings.getKeyStore(), password); KeyManager[] keyManagers = keyManagerFactory.getKeyManagers(); Client proxy = ClientProxy.getClient(localEjbcaWS); TLSClientParameters tlsClientParameters = new TLSClientParameters(); tlsClientParameters.setDisableCNCheck(requestHandlerSettings.isDisableCNCheck()); if (requestHandlerSettings.isSkipCertificateCheck()) { /* * Use a TrustManager that skips all checks */ tlsClientParameters.setTrustManagers(new TrustManager[] { new TrustAllX509TrustManager() }); } else { KeyStore trustStore = requestHandlerSettings.getTrustStore(); if (trustStore != null) { /* * Use the provided trust store */ TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); tlsClientParameters.setTrustManagers(trustManagerFactory.getTrustManagers()); } } tlsClientParameters.setKeyManagers(keyManagers); HTTPConduit conduit = (HTTPConduit) proxy.getConduit(); conduit.setTlsClientParameters(tlsClientParameters); ejbcaWS = localEjbcaWS; } catch (NoSuchAlgorithmException e) { throw new CAException(e); } catch (UnrecoverableKeyException e) { throw new CAException(e); } catch (KeyStoreException e) { throw new CAException(e); } } return ejbcaWS; }