use of javax.net.ssl.KeyManagerFactory in project nifi by apache.
the class InvokeHTTP method setSslSocketFactory.
/*
Overall, this method is based off of examples from OkHttp3 documentation:
https://square.github.io/okhttp/3.x/okhttp/okhttp3/OkHttpClient.Builder.html#sslSocketFactory-javax.net.ssl.SSLSocketFactory-javax.net.ssl.X509TrustManager-
https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/CustomTrust.java#L156
In-depth documentation on Java Secure Socket Extension (JSSE) Classes and interfaces:
https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html#JSSEClasses
*/
private void setSslSocketFactory(OkHttpClient.Builder okHttpClientBuilder, SSLContextService sslService, SSLContext sslContext, boolean setAsSocketFactory) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException {
final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509");
// initialize the KeyManager array to null and we will overwrite later if a keystore is loaded
KeyManager[] keyManagers = null;
// we will only initialize the keystore if properties have been supplied by the SSLContextService
if (sslService.isKeyStoreConfigured()) {
final String keystoreLocation = sslService.getKeyStoreFile();
final String keystorePass = sslService.getKeyStorePassword();
final String keystoreType = sslService.getKeyStoreType();
// prepare the keystore
final KeyStore keyStore = KeyStore.getInstance(keystoreType);
try (FileInputStream keyStoreStream = new FileInputStream(keystoreLocation)) {
keyStore.load(keyStoreStream, keystorePass.toCharArray());
}
keyManagerFactory.init(keyStore, keystorePass.toCharArray());
keyManagers = keyManagerFactory.getKeyManagers();
}
// we will only initialize the truststure if properties have been supplied by the SSLContextService
if (sslService.isTrustStoreConfigured()) {
// load truststore
final String truststoreLocation = sslService.getTrustStoreFile();
final String truststorePass = sslService.getTrustStorePassword();
final String truststoreType = sslService.getTrustStoreType();
KeyStore truststore = KeyStore.getInstance(truststoreType);
truststore.load(new FileInputStream(truststoreLocation), truststorePass.toCharArray());
trustManagerFactory.init(truststore);
}
/*
TrustManagerFactory.getTrustManagers returns a trust manager for each type of trust material. Since we are getting a trust manager factory that uses "X509"
as it's trust management algorithm, we are able to grab the first (and thus the most preferred) and use it as our x509 Trust Manager
https://docs.oracle.com/javase/8/docs/api/javax/net/ssl/TrustManagerFactory.html#getTrustManagers--
*/
final X509TrustManager x509TrustManager;
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
if (trustManagers[0] != null) {
x509TrustManager = (X509TrustManager) trustManagers[0];
} else {
throw new IllegalStateException("List of trust managers is null");
}
// if keystore properties were not supplied, the keyManagers array will be null
sslContext.init(keyManagers, trustManagerFactory.getTrustManagers(), null);
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
okHttpClientBuilder.sslSocketFactory(sslSocketFactory, x509TrustManager);
if (setAsSocketFactory) {
okHttpClientBuilder.socketFactory(sslSocketFactory);
}
}
use of javax.net.ssl.KeyManagerFactory in project nifi by apache.
the class TestGRPCServer method start.
/**
* Starts the gRPC server @localhost:port.
*/
public int start(final int port) throws Exception {
final NettyServerBuilder nettyServerBuilder = NettyServerBuilder.forPort(port).directExecutor().addService(clazz.newInstance()).compressorRegistry(CompressorRegistry.getDefaultInstance()).decompressorRegistry(DecompressorRegistry.getDefaultInstance());
if (this.sslProperties != null) {
if (sslProperties.get(StandardSSLContextService.KEYSTORE.getName()) == null) {
throw new RuntimeException("You must configure a keystore in order to use SSL with gRPC.");
}
final KeyManagerFactory keyManager = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
final KeyStore keyStore = KeyStore.getInstance(sslProperties.get(StandardSSLContextService.KEYSTORE_TYPE.getName()));
final String keyStoreFile = sslProperties.get(StandardSSLContextService.KEYSTORE.getName());
final String keyStorePassword = sslProperties.get(StandardSSLContextService.KEYSTORE_PASSWORD.getName());
try (final InputStream is = new FileInputStream(keyStoreFile)) {
keyStore.load(is, keyStorePassword.toCharArray());
}
keyManager.init(keyStore, keyStorePassword.toCharArray());
SslContextBuilder sslContextBuilder = SslContextBuilder.forServer(keyManager);
if (sslProperties.get(StandardSSLContextService.TRUSTSTORE.getName()) != null) {
final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
final KeyStore trustStore = KeyStore.getInstance(sslProperties.get(StandardSSLContextService.TRUSTSTORE_TYPE.getName()));
final String trustStoreFile = sslProperties.get(StandardSSLContextService.TRUSTSTORE.getName());
final String trustStorePassword = sslProperties.get(StandardSSLContextService.TRUSTSTORE_PASSWORD.getName());
try (final InputStream is = new FileInputStream(trustStoreFile)) {
trustStore.load(is, trustStorePassword.toCharArray());
}
trustManagerFactory.init(trustStore);
sslContextBuilder = sslContextBuilder.trustManager(trustManagerFactory);
}
final String clientAuth = sslProperties.get(NEED_CLIENT_AUTH);
if (clientAuth == null) {
sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.REQUIRE);
} else {
sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.valueOf(clientAuth));
}
sslContextBuilder = GrpcSslContexts.configure(sslContextBuilder);
nettyServerBuilder.sslContext(sslContextBuilder.build());
}
server = nettyServerBuilder.build().start();
final int actualPort = server.getPort();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
// Use stderr here since the logger may have been reset by its JVM shutdown hook.
System.err.println("*** shutting down gRPC server since JVM is shutting down");
TestGRPCServer.this.stop();
System.err.println("*** server shut down");
}
});
return actualPort;
}
use of javax.net.ssl.KeyManagerFactory in project webpieces by deanhiller.
the class WebSSLFactory method createSslEngine.
@Override
public SSLEngine createSslEngine() {
// Create/startPing the SSLContext with key material
try (InputStream keySt = WebSSLFactory.class.getResourceAsStream(serverKeystore)) {
char[] passphrase = password.toCharArray();
// First startPing the key and trust material.
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(keySt, passphrase);
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
//****************Server side specific*********************
// KeyManager's decide which key material to use.
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, passphrase);
sslContext.init(kmf.getKeyManagers(), null, null);
//****************Server side specific*********************
SSLEngine engine = sslContext.createSSLEngine();
engine.setUseClientMode(false);
return engine;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
use of javax.net.ssl.KeyManagerFactory in project geode by apache.
the class SocketCreator method getKeyManagers.
private KeyManager[] getKeyManagers() throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException {
GfeConsoleReader consoleReader = GfeConsoleReaderFactory.getDefaultConsoleReader();
KeyManager[] keyManagers = null;
String keyStoreType = sslConfig.getKeystoreType();
if (StringUtils.isEmpty(keyStoreType)) {
// read from console, default on empty
if (consoleReader.isSupported()) {
keyStoreType = consoleReader.readLine("Please enter the keyStoreType (javax.net.ssl.keyStoreType) : ");
} else {
keyStoreType = KeyStore.getDefaultType();
}
}
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
String keyStoreFilePath = sslConfig.getKeystore();
if (StringUtils.isEmpty(keyStoreFilePath)) {
if (consoleReader.isSupported()) {
keyStoreFilePath = consoleReader.readLine("Please enter the keyStore location (javax.net.ssl.keyStore) : ");
} else {
keyStoreFilePath = System.getProperty("user.home") + System.getProperty("file.separator") + ".keystore";
}
}
FileInputStream fileInputStream = new FileInputStream(keyStoreFilePath);
String passwordString = sslConfig.getKeystorePassword();
char[] password = null;
if (passwordString != null) {
if (passwordString.trim().equals("")) {
String encryptedPass = System.getenv("javax.net.ssl.keyStorePassword");
if (!StringUtils.isEmpty(encryptedPass)) {
String toDecrypt = "encrypted(" + encryptedPass + ")";
passwordString = PasswordUtil.decrypt(toDecrypt);
password = passwordString.toCharArray();
}
// read from the console
if (StringUtils.isEmpty(passwordString) && consoleReader != null) {
password = consoleReader.readPassword("Please enter password for keyStore (javax.net.ssl.keyStorePassword) : ");
}
} else {
password = passwordString.toCharArray();
}
}
keyStore.load(fileInputStream, password);
// default algorithm can be changed by setting property "ssl.KeyManagerFactory.algorithm" in
// security properties
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, password);
keyManagers = keyManagerFactory.getKeyManagers();
// follow the security tip in java doc
if (password != null) {
java.util.Arrays.fill(password, ' ');
}
KeyManager[] extendedKeyManagers = new KeyManager[keyManagers.length];
for (int i = 0; i < keyManagers.length; i++) {
extendedKeyManagers[i] = new ExtendedAliasKeyManager(keyManagers[i], sslConfig.getAlias());
}
return extendedKeyManagers;
}
use of javax.net.ssl.KeyManagerFactory in project wso2-axis2-transports by wso2.
the class RabbitMQConnectionFactory method initConnectionFactory.
/**
* Initialize connection factory
*/
private void initConnectionFactory() {
connectionFactory = new ConnectionFactory();
String hostName = parameters.get(RabbitMQConstants.SERVER_HOST_NAME);
String portValue = parameters.get(RabbitMQConstants.SERVER_PORT);
String serverRetryIntervalS = parameters.get(RabbitMQConstants.SERVER_RETRY_INTERVAL);
String retryIntervalS = parameters.get(RabbitMQConstants.RETRY_INTERVAL);
String retryCountS = parameters.get(RabbitMQConstants.RETRY_COUNT);
String heartbeat = parameters.get(RabbitMQConstants.HEARTBEAT);
String connectionTimeout = parameters.get(RabbitMQConstants.CONNECTION_TIMEOUT);
String sslEnabledS = parameters.get(RabbitMQConstants.SSL_ENABLED);
String userName = parameters.get(RabbitMQConstants.SERVER_USER_NAME);
String password = parameters.get(RabbitMQConstants.SERVER_PASSWORD);
String virtualHost = parameters.get(RabbitMQConstants.SERVER_VIRTUAL_HOST);
String connectionPoolSizeS = parameters.get(RabbitMQConstants.CONNECTION_POOL_SIZE);
if (!StringUtils.isEmpty(heartbeat)) {
try {
int heartbeatValue = Integer.parseInt(heartbeat);
connectionFactory.setRequestedHeartbeat(heartbeatValue);
} catch (NumberFormatException e) {
// proceeding with rabbitmq default value
log.warn("Number format error in reading heartbeat value. Proceeding with default");
}
}
if (!StringUtils.isEmpty(connectionTimeout)) {
try {
int connectionTimeoutValue = Integer.parseInt(connectionTimeout);
connectionFactory.setConnectionTimeout(connectionTimeoutValue);
} catch (NumberFormatException e) {
// proceeding with rabbitmq default value
log.warn("Number format error in reading connection timeout value. Proceeding with default");
}
}
if (!StringUtils.isEmpty(connectionPoolSizeS)) {
try {
connectionPoolSize = Integer.parseInt(connectionPoolSizeS);
} catch (NumberFormatException e) {
// proceeding with rabbitmq default value
log.warn("Number format error in reading connection timeout value. Proceeding with default");
}
}
if (!StringUtils.isEmpty(sslEnabledS)) {
try {
boolean sslEnabled = Boolean.parseBoolean(sslEnabledS);
if (sslEnabled) {
String keyStoreLocation = parameters.get(RabbitMQConstants.SSL_KEYSTORE_LOCATION);
String keyStoreType = parameters.get(RabbitMQConstants.SSL_KEYSTORE_TYPE);
String keyStorePassword = parameters.get(RabbitMQConstants.SSL_KEYSTORE_PASSWORD);
String trustStoreLocation = parameters.get(RabbitMQConstants.SSL_TRUSTSTORE_LOCATION);
String trustStoreType = parameters.get(RabbitMQConstants.SSL_TRUSTSTORE_TYPE);
String trustStorePassword = parameters.get(RabbitMQConstants.SSL_TRUSTSTORE_PASSWORD);
String sslVersion = parameters.get(RabbitMQConstants.SSL_VERSION);
if (StringUtils.isEmpty(keyStoreLocation) || StringUtils.isEmpty(keyStoreType) || StringUtils.isEmpty(keyStorePassword) || StringUtils.isEmpty(trustStoreLocation) || StringUtils.isEmpty(trustStoreType) || StringUtils.isEmpty(trustStorePassword)) {
log.info("Trustore 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 c = SSLContext.getInstance(sslVersion);
c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
connectionFactory.useSslProtocol(c);
}
}
} catch (Exception e) {
log.warn("Format error in SSL enabled value. Proceeding without enabling SSL", e);
}
}
if (!StringUtils.isEmpty(retryCountS)) {
try {
retryCount = Integer.parseInt(retryCountS);
} catch (NumberFormatException e) {
log.warn("Number format error in reading retry count value. Proceeding with default value (3)", e);
}
}
// Resolving hostname(s) and port(s)
if (!StringUtils.isEmpty(hostName) && !StringUtils.isEmpty(portValue)) {
String[] hostNames = hostName.split(",");
String[] portValues = portValue.split(",");
if (hostNames.length == portValues.length) {
addresses = new Address[hostNames.length];
for (int i = 0; i < hostNames.length; i++) {
if (!hostNames[i].isEmpty() && !portValues[i].isEmpty()) {
try {
addresses[i] = new Address(hostNames[i].trim(), Integer.parseInt(portValues[i].trim()));
} catch (NumberFormatException e) {
handleException("Number format error in port number", e);
}
}
}
}
} else {
handleException("Host name(s) and port(s) are not correctly defined");
}
if (!StringUtils.isEmpty(userName)) {
connectionFactory.setUsername(userName);
}
if (!StringUtils.isEmpty(password)) {
connectionFactory.setPassword(password);
}
if (!StringUtils.isEmpty(virtualHost)) {
connectionFactory.setVirtualHost(virtualHost);
}
if (!StringUtils.isEmpty(retryIntervalS)) {
try {
retryInterval = Integer.parseInt(retryIntervalS);
} catch (NumberFormatException e) {
log.warn("Number format error in reading retry interval value. Proceeding with default value (30000ms)", e);
}
}
if (!StringUtils.isEmpty(serverRetryIntervalS)) {
try {
int serverRetryInterval = Integer.parseInt(serverRetryIntervalS);
connectionFactory.setNetworkRecoveryInterval(serverRetryInterval);
} catch (NumberFormatException e) {
log.warn("Number format error in reading server retry interval value. Proceeding with default value", e);
}
}
connectionFactory.setAutomaticRecoveryEnabled(true);
connectionFactory.setTopologyRecoveryEnabled(false);
}
Aggregations