Java Code Examples for javax.net.ssl.KeyManager

The following are top voted examples for showing how to use javax.net.ssl.KeyManager. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: framework   File: HttpClientUtil.java   View source code 11 votes vote down vote up
@PostConstruct
public void afterPropertiesSet() throws Exception {
	RegistryBuilder<ConnectionSocketFactory> schemeRegistry = RegistryBuilder.create();

	schemeRegistry.register("http", PlainConnectionSocketFactory.getSocketFactory());

	SSLContext sslcontext = SSLContext.getInstance("TLS");
	sslcontext.init(new KeyManager[0], new TrustManager[]{new SimpleTrustManager()}, null);
	SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslcontext);
	schemeRegistry.register("https", sf);

	pool = new PoolingHttpClientConnectionManager(schemeRegistry.build());
	pool.setMaxTotal(maxConnection);
	pool.setDefaultMaxPerRoute(maxConnection);
	pool.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(sotimeout).build());
}
 
Example 2
Project: openjdk-jdk10   File: EmptyCertificateAuthorities.java   View source code 7 votes vote down vote up
private SSLServerSocketFactory getSSLServerSF() throws Exception {

        char [] password =
            System.getProperty("javax.net.ssl.keyStorePassword").toCharArray();
        String keyFilename = System.getProperty("javax.net.ssl.keyStore");

        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(new FileInputStream(keyFilename), password);

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
        kmf.init(ks, password);

        KeyManager[] kms = kmf.getKeyManagers();
        TrustManager[] tms = new MyX509TM[] {new MyX509TM()};

        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(kms, tms, null);

        return ctx.getServerSocketFactory();
    }
 
Example 3
Project: lazycat   File: NioEndpoint.java   View source code 6 votes vote down vote up
public KeyManager[] wrap(KeyManager[] managers) {
	if (managers == null)
		return null;
	KeyManager[] result = new KeyManager[managers.length];
	for (int i = 0; i < result.length; i++) {
		if (managers[i] instanceof X509KeyManager && getKeyAlias() != null) {
			String keyAlias = getKeyAlias();
			// JKS keystores always convert the alias name to lower case
			if ("jks".equalsIgnoreCase(getKeystoreType())) {
				keyAlias = keyAlias.toLowerCase(Locale.ENGLISH);
			}
			result[i] = new NioX509KeyManager((X509KeyManager) managers[i], keyAlias);
		} else {
			result[i] = managers[i];
		}
	}
	return result;
}
 
Example 4
Project: incubator-servicecomb-java-chassis   File: KeyStoreUtil.java   View source code 6 votes vote down vote up
public static KeyManager[] createKeyManagers(final KeyStore keystore,
    char[] keyvalue) {
  try {
    KeyManagerFactory kmfactory =
        KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmfactory.init(keystore, keyvalue);
    return kmfactory.getKeyManagers();
  } catch (Exception e) {
    throw new IllegalArgumentException("Bad key store."
        + e.getMessage());
  }
}
 
Example 5
Project: mobile-store   File: LocalRepoKeyStore.java   View source code 6 votes vote down vote up
private void addToStore(String alias, KeyPair kp, Certificate cert) throws KeyStoreException,
        NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException {
    Certificate[] chain = {
        cert,
    };
    keyStore.setKeyEntry(alias, kp.getPrivate(),
            "".toCharArray(), chain);

    keyStore.store(new FileOutputStream(keyStoreFile), "".toCharArray());

    /*
     * After adding an entry to the keystore we need to create a fresh
     * KeyManager by reinitializing the KeyManagerFactory with the new key
     * store content and then rewrapping the default KeyManager with our own
     */
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());

    keyManagerFactory.init(keyStore, "".toCharArray());
    KeyManager defaultKeyManager = keyManagerFactory.getKeyManagers()[0];
    KeyManager wrappedKeyManager = new KerplappKeyManager((X509KeyManager) defaultKeyManager);
    keyManagers = new KeyManager[] {
        wrappedKeyManager,
    };
}
 
Example 6
Project: drift   File: ApacheThriftMethodInvokerFactory.java   View source code 6 votes vote down vote up
private static SSLContext createSslContext(ApacheThriftClientConfig config)
{
    try {
        KeyStore trustStore = loadTrustStore(config.getTrustCertificate());
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        KeyManager[] keyManagers = null;
        if (config.getKey() != null) {
            Optional<String> keyPassword = Optional.ofNullable(config.getKeyPassword());
            KeyStore keyStore = loadKeyStore(config.getTrustCertificate(), config.getKey(), keyPassword);
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, new char[0]);
            keyManagers = keyManagerFactory.getKeyManagers();
        }

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagers, trustManagerFactory.getTrustManagers(), null);
        return sslContext;
    }
    catch (IOException | GeneralSecurityException e) {
        throw new IllegalArgumentException("Unable to load SSL keys", e);
    }
}
 
Example 7
Project: rxjava2_retrofit2   File: CustomHttpsTrust.java   View source code 6 votes vote down vote up
/**
 * 双向证书的验证,极少数的应用需要双向证书验证,比如银行、金融类
 *
 * @param certificates
 * @param bksFile
 * @param password
 */
public CustomHttpsTrust(InputStream[] certificates, InputStream bksFile, String password) {

    try {
        TrustManager[] trustManagers = prepareTrustManager(certificates);
        KeyManager[] keyManagers = prepareKeyManager(bksFile, password);
        if (trustManagers == null) {
            x509TrustManager = new UnSafeTrustManager();
        } else {
            for (TrustManager trustManager :
                    trustManagers) {
                if (trustManager instanceof X509TrustManager) {
                    x509TrustManager = (X509TrustManager) trustManager;
                    break;
                }
            }
        }
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagers, new TrustManager[]{x509TrustManager}, null);
        sSLSocketFactory = sslContext.getSocketFactory();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 8
Project: rxjava2_retrofit2   File: CustomHttpsTrust.java   View source code 6 votes vote down vote up
private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) {

        if (bksFile == null || password == null) {
            return null;
        }

        KeyStore clientKeyStore;
        try {
            clientKeyStore = KeyStore.getInstance("BKS");
            clientKeyStore.load(bksFile, password.toCharArray());
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(clientKeyStore, password.toCharArray());
            return keyManagerFactory.getKeyManagers();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
Example 9
Project: rxjava2_retrofit2   File: HttpsUtils.java   View source code 6 votes vote down vote up
public static SSLParams getSslSocketFactory(InputStream[] certificates, InputStream bksFile, String password) {
    SSLParams sslParams = new SSLParams();
    try {
        TrustManager[] trustManagers = prepareTrustManager(certificates);
        KeyManager[] keyManagers = prepareKeyManager(bksFile, password);
        SSLContext sslContext = SSLContext.getInstance("TLS");
        X509TrustManager trustManager = null;
        if (trustManagers != null) {
            trustManager = new MyTrustManager(chooseTrustManager(trustManagers));
        } else {
            trustManager = new UnSafeTrustManager();
        }
        sslContext.init(keyManagers, new TrustManager[]{trustManager}, null);
        sslParams.sSLSocketFactory = sslContext.getSocketFactory();
        sslParams.trustManager = trustManager;
        return sslParams;
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
        throw new AssertionError(e);
    }
}
 
Example 10
Project: RoughWorld   File: WebInterfaceSSL.java   View source code 6 votes vote down vote up
public static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManager[] keyManagers)
{
    SSLServerSocketFactory res = null;
    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(loadedKeyStore);
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(keyManagers, trustManagerFactory.getTrustManagers(), null);
        res = ctx.getServerSocketFactory();
    } 
    catch (Exception e) 
    {
    	System.out.println(e.toString());
        //throw new IOException(e.getMessage());
    }
    return res;
}
 
Example 11
Project: alfresco-core   File: AuthSSLProtocolSocketFactory.java   View source code 6 votes vote down vote up
private SSLContext createSSLContext()
{
    KeyManager[] keymanagers = keyStore.createKeyManagers();;
    TrustManager[] trustmanagers = trustStore.createTrustManagers();

    try
    {
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    }
    catch(Throwable e)
    {
        throw new AlfrescoRuntimeException("Unable to create SSL context", e);
    }
}
 
Example 12
Project: spur   File: SpurOptions.java   View source code 6 votes vote down vote up
private static SSLContext createSSLContext(final KeyStore keyStore, final KeyStore trustStore, String password) throws Exception {
    KeyManager[] keyManagers;
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, password.toCharArray());
    keyManagers = keyManagerFactory.getKeyManagers();

    TrustManager[] trustManagers;
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);
    trustManagers = trustManagerFactory.getTrustManagers();

    SSLContext sslContext;
    sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagers, trustManagers, null);

    return sslContext;
}
 
Example 13
Project: MQTT-Essentials-A-Lightweight-IoT-Protocol   File: SecurityHelper.java   View source code 6 votes vote down vote up
public static SSLSocketFactory createSocketFactory(
	final String caCertificateFileName, 
	final String clientCertificateFileName, 
	final String clientKeyFileName) throws Exception
{
	// Creates a TLS socket factory with the given 
	// CA certificate file, client certificate, client key
	// In this case, we are working without a client key password
	final String clientKeyPassword = "";
	try
	{
		Security.addProvider(new BouncyCastleProvider());
		final KeyManager[] keyManagers = createKeyManagerFactory(clientCertificateFileName, clientKeyFileName, clientKeyPassword).getKeyManagers();
		final TrustManager[] trustManagers = createTrustManagerFactory(caCertificateFileName).getTrustManagers();
		
		// Create the TLS socket factory for the desired TLS version
		final SSLContext context = SSLContext.getInstance(TLS_VERSION);
		
		context.init(keyManagers, trustManagers, new SecureRandom());
		//context.init(keyManagers, trustManagers, null);

		return context.getSocketFactory();			
	}
	catch (Exception e)
	{
		throw new Exception("I cannot create the TLS socket factory.", e);
	}		
}
 
Example 14
Project: syndesis   File: ActiveMQUtilTest.java   View source code 6 votes vote down vote up
@Test
    public void createKeyManagers() throws Exception {
/*
        StringBuffer sb = new StringBuffer();
        Provider[] p = Security.getProviders();
        for (int i = 0; i < p.length; i++) {
            sb.append("\nProvider : " + p[i].toString() + "\n");
            Set s = p[i].keySet();
            Object[] o = s.toArray();
            Arrays.sort(o);
            for (int j = 1; j < o.length; j++) {
                sb.append(o[j].toString() + ", ");
            }
        }
        System.out.println(sb.toString());
*/
        final KeyManager[] keyManagers = ActiveMQUtil.createKeyManagers(TEST_CERT);
        assertThat(keyManagers).isNotNull().isNotEmpty();
    }
 
Example 15
Project: nifi-android-s2s   File: SiteToSiteRemoteCluster.java   View source code 6 votes vote down vote up
/**
 * Gets the ssl context for use making the connections
 *
 * @return the ssl context
 */
public SSLContext getSslContext() {
    KeyManager[] keyManagers = getKeyManagers();
    TrustManager[] trustManagers = getTrustManagers();
    if (keyManagers != null || trustManagers != null) {
        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(getKeyManagers(), trustManagers, null);
            sslContext.getDefaultSSLParameters().setNeedClientAuth(true);
            return sslContext;
        } catch (Exception e) {
            throw new IllegalStateException("Created keystore and truststore but failed to initialize SSLContext", e);
        }
    } else {
        return null;
    }
}
 
Example 16
Project: SmartChart   File: HttpsUtils.java   View source code 6 votes vote down vote up
public static SSLParams getSslSocketFactory(InputStream[] certificates, InputStream bksFile, String password) {
    SSLParams sslParams = new SSLParams();
    try {
        TrustManager[] trustManagers = prepareTrustManager(certificates);
        KeyManager[] keyManagers = prepareKeyManager(bksFile, password);
        SSLContext sslContext = SSLContext.getInstance("TLS");
        X509TrustManager trustManager = null;
        if (trustManagers != null) {
            trustManager = new MyTrustManager(chooseTrustManager(trustManagers));
        } else {
            trustManager = new UnSafeTrustManager();
        }
        sslContext.init(keyManagers, new TrustManager[]{trustManager}, null);
        sslParams.sSLSocketFactory = sslContext.getSocketFactory();
        sslParams.trustManager = trustManager;
        return sslParams;
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
        throw new AssertionError(e);
    }
}
 
Example 17
Project: wx-idk   File: HttpsRequestTools.java   View source code 6 votes vote down vote up
/**
   * 创建Http/Https请求对象
   * @author Rocye
   * @param url 请求地址
   * @param method 请求方式:GET/POST
   * @param certPath 证书路径
   * @param certPass 证书密码
* @param useCert 是否需要证书
   * @return Https连接
   * @throws Exception 任何异常
   * @version 2017.11.14
   */
  private HttpsURLConnection createRequest(String url, String method, String certPath, String certPass, boolean useCert) throws Exception{
      URL realUrl = new URL(url);
      HttpsURLConnection connection = (HttpsURLConnection)realUrl.openConnection();

      //设置证书
if(useCert){
	KeyStore clientStore = KeyStore.getInstance("PKCS12");
	InputStream inputStream = new FileInputStream(certPath);
	clientStore.load(inputStream, certPass.toCharArray());
	KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	kmf.init(clientStore, certPass.toCharArray());
	KeyManager[] kms = kmf.getKeyManagers();
	SSLContext sslContext = SSLContext.getInstance("TLSv1");
	sslContext.init(kms, null, new SecureRandom());
	connection.setSSLSocketFactory(sslContext.getSocketFactory());
}

      // 设置通用的请求属性
      connection.setRequestProperty("Accept", "*/*");
      connection.setRequestProperty("Connection", "Keep-Alive");
      connection.setConnectTimeout(this.connectTimeout);
      connection.setReadTimeout(this.readTimeout);
      if("POST".equals(method)){
          // 发送POST请求必须设置如下两行
          connection.setDoOutput(true);
          connection.setDoInput(true);
          connection.setUseCaches(false);   // 忽略缓存
          connection.setRequestMethod("POST");
      }
      return connection;
  }
 
Example 18
Project: apache-tomcat-7.0.73-with-comment   File: NioEndpoint.java   View source code 6 votes vote down vote up
public KeyManager[] wrap(KeyManager[] managers) {
    if (managers==null) return null;
    KeyManager[] result = new KeyManager[managers.length];
    for (int i=0; i<result.length; i++) {
        if (managers[i] instanceof X509KeyManager && getKeyAlias()!=null) {
            String keyAlias = getKeyAlias();
            // JKS keystores always convert the alias name to lower case
            if ("jks".equalsIgnoreCase(getKeystoreType())) {
                keyAlias = keyAlias.toLowerCase(Locale.ENGLISH);
            }
            result[i] = new NioX509KeyManager((X509KeyManager) managers[i], keyAlias);
        } else {
            result[i] = managers[i];
        }
    }
    return result;
}
 
Example 19
Project: jdk8u-jdk   File: JSSEServer.java   View source code 6 votes vote down vote up
JSSEServer(CipherTestUtils cipherTest, int serverPort,
        String protocol, String cipherSuite) throws Exception {
    super(cipherTest);
    this.serverPort = serverPort;
    SSLContext serverContext = SSLContext.getInstance("TLS");
    serverContext.init(new KeyManager[]{cipherTest.getServerKeyManager()},
            new TrustManager[]{cipherTest.getServerTrustManager()},
            CipherTestUtils.secureRandom);
    SSLServerSocketFactory factory =
            (SSLServerSocketFactory)serverContext.getServerSocketFactory();
    serverSocket =
            (SSLServerSocket) factory.createServerSocket(serverPort);
    serverSocket.setEnabledProtocols(protocol.split(","));
    serverSocket.setEnabledCipherSuites(cipherSuite.split(","));

    CipherTestUtils.printInfo(serverSocket);
}
 
Example 20
Project: openjdk-jdk10   File: JSSEServer.java   View source code 6 votes vote down vote up
JSSEServer(CipherTestUtils cipherTest, int serverPort,
        String protocol, String cipherSuite) throws Exception {
    super(cipherTest);
    SSLContext serverContext = SSLContext.getInstance("TLS");
    serverContext.init(new KeyManager[]{cipherTest.getServerKeyManager()},
            new TrustManager[]{cipherTest.getServerTrustManager()},
            CipherTestUtils.secureRandom);
    SSLServerSocketFactory factory =
            (SSLServerSocketFactory)serverContext.getServerSocketFactory();
    serverSocket =
            (SSLServerSocket) factory.createServerSocket(serverPort);
    serverSocket.setEnabledProtocols(protocol.split(","));
    serverSocket.setEnabledCipherSuites(cipherSuite.split(","));

    CipherTestUtils.printInfo(serverSocket);
}
 
Example 21
Project: jetfuel   File: X509CertificateWithKey.java   View source code 5 votes vote down vote up
public final SSLSocketFactory createSocketFactoryForBlindlyTrustedServer()
		throws NoSuchAlgorithmException,
			KeyManagementException {
	SSLContext sc = SSLContext.getInstance("TLS");
	sc.init(
			new KeyManager[] {
					new X509KeyManager(certificate, privateKey)
			},
			new TrustManager[] {
					new X509TrustManager()
			},
			new SecureRandom());
	return sc.getSocketFactory();
}
 
Example 22
Project: GitHub   File: HttpsUtils.java   View source code 5 votes vote down vote up
private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) {
    try {
        if (bksFile == null || password == null) return null;
        KeyStore clientKeyStore = KeyStore.getInstance("BKS");
        clientKeyStore.load(bksFile, password.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(clientKeyStore, password.toCharArray());
        return kmf.getKeyManagers();
    } catch (Exception e) {
        OkLogger.printStackTrace(e);
    }
    return null;
}
 
Example 23
Project: VBrowser-Android   File: NanoHTTPD.java   View source code 5 votes vote down vote up
/**
 * Creates an SSLSocketFactory for HTTPS. Pass a loaded KeyStore and an
 * array of loaded KeyManagers. These objects must properly
 * loaded/initialized by the caller.
 */
public static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManager[] keyManagers) throws IOException {
    SSLServerSocketFactory res = null;
    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(loadedKeyStore);
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(keyManagers, trustManagerFactory.getTrustManagers(), null);
        res = ctx.getServerSocketFactory();
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
    return res;
}
 
Example 24
Project: springboot-shiro-cas-mybatis   File: FileTrustStoreSslSocketFactory.java   View source code 5 votes vote down vote up
/**
 * Gets the trusted ssl context.
 *
 * @param trustStoreFile the trust store file
 * @param trustStorePassword the trust store password
 * @param trustStoreType the trust store type
 * @return the trusted ssl context
 */
private static SSLContext getTrustedSslContext(final File trustStoreFile, final String trustStorePassword,
                                        final String trustStoreType) {
    try {

        if (!trustStoreFile.exists() || !trustStoreFile.canRead()) {
            throw new FileNotFoundException("Truststore file cannot be located at "
                + trustStoreFile.getCanonicalPath());
        }

        final KeyStore casTrustStore = KeyStore.getInstance(trustStoreType);
        final char[] trustStorePasswordCharArray = trustStorePassword.toCharArray();

        try (FileInputStream casStream = new FileInputStream(trustStoreFile)) {
            casTrustStore.load(casStream, trustStorePasswordCharArray);
        }

        final String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
        final X509KeyManager customKeyManager = getKeyManager("PKIX", casTrustStore, trustStorePasswordCharArray);
        final X509KeyManager jvmKeyManager = getKeyManager(defaultAlgorithm, null, null);
        final X509TrustManager customTrustManager = getTrustManager("PKIX", casTrustStore);
        final X509TrustManager jvmTrustManager = getTrustManager(defaultAlgorithm, null);

        final KeyManager[] keyManagers = {
                new CompositeX509KeyManager(Arrays.asList(jvmKeyManager, customKeyManager))
        };
        final TrustManager[] trustManagers = {
                new CompositeX509TrustManager(Arrays.asList(jvmTrustManager, customTrustManager))
        };

        final SSLContext context = SSLContexts.custom().useSSL().build();
        context.init(keyManagers, trustManagers, null);
        return context;

    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}
 
Example 25
Project: springboot-shiro-cas-mybatis   File: FileTrustStoreSslSocketFactory.java   View source code 5 votes vote down vote up
/**
 * Gets the trusted ssl context.
 *
 * @param trustStoreFile the trust store file
 * @param trustStorePassword the trust store password
 * @param trustStoreType the trust store type
 * @return the trusted ssl context
 */
private static SSLContext getTrustedSslContext(final File trustStoreFile, final String trustStorePassword,
                                        final String trustStoreType) {
    try {

        if (!trustStoreFile.exists() || !trustStoreFile.canRead()) {
            throw new FileNotFoundException("Truststore file cannot be located at " + trustStoreFile.getCanonicalPath());
        }

        final KeyStore casTrustStore = KeyStore.getInstance(trustStoreType);
        final char[] trustStorePasswordCharArray = trustStorePassword.toCharArray();

        try (final FileInputStream casStream = new FileInputStream(trustStoreFile)) {
            casTrustStore.load(casStream, trustStorePasswordCharArray);
        }

        final String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
        final X509KeyManager customKeyManager = getKeyManager("PKIX", casTrustStore, trustStorePasswordCharArray);
        final X509KeyManager jvmKeyManager = getKeyManager(defaultAlgorithm, null, null);
        final X509TrustManager customTrustManager = getTrustManager("PKIX", casTrustStore);
        final X509TrustManager jvmTrustManager = getTrustManager(defaultAlgorithm, null);

        final KeyManager[] keyManagers = {
                new CompositeX509KeyManager(Arrays.asList(jvmKeyManager, customKeyManager))
        };
        final TrustManager[] trustManagers = {
                new CompositeX509TrustManager(Arrays.asList(jvmTrustManager, customTrustManager))
        };

        final SSLContext context = SSLContexts.custom().useSSL().build();
        context.init(keyManagers, trustManagers, null);
        return context;

    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}
 
Example 26
Project: ultrasonic   File: SSLSocketFactory.java   View source code 5 votes vote down vote up
private static SSLContext createSSLContext(String algorithm, final KeyStore keystore, final String keyStorePassword, final SecureRandom random, final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException
{
	if (algorithm == null)
	{
		algorithm = TLS;
	}

	KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	keyManagerFactory.init(keystore, keyStorePassword != null ? keyStorePassword.toCharArray() : null);
	KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
	TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
	trustManagerFactory.init(keystore);

	TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

	if (trustManagers != null && trustStrategy != null)
	{
		for (int i = 0; i < trustManagers.length; i++)
		{
			TrustManager tm = trustManagers[i];

			if (tm instanceof X509TrustManager)
			{
				trustManagers[i] = new TrustManagerDecorator((X509TrustManager) tm, trustStrategy);
			}
		}
	}

	SSLContext sslcontext = SSLContext.getInstance(algorithm);
	sslcontext.init(keyManagers, trustManagers, random);

	return sslcontext;
}
 
Example 27
Project: java-buildpack-security-provider   File: FileWatchingX509ExtendedKeyManager.java   View source code 5 votes vote down vote up
private X509ExtendedKeyManager getKeyManager(KeyStore keyStore) {
    try {
        this.keyManagerFactory.init(keyStore, new char[0]);

        for (KeyManager keyManager : this.keyManagerFactory.getKeyManagers()) {
            if (keyManager instanceof X509ExtendedKeyManager) {
                return (X509ExtendedKeyManager) keyManager;
            }
        }

        throw new IllegalStateException("No X509ExtendedKeyManager available");
    } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) {
        throw new UndeclaredThrowableException(e);
    }
}
 
Example 28
Project: EvolvingNetLib   File: HttpsUtil.java   View source code 5 votes vote down vote up
private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) {
    try {
        if (bksFile == null || password == null) return null;
        KeyStore clientKeyStore = KeyStore.getInstance("BKS");
        clientKeyStore.load(bksFile, password.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(clientKeyStore, password.toCharArray());
        return kmf.getKeyManagers();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 29
Project: SuperHttp   File: HttpsUtils.java   View source code 5 votes vote down vote up
private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) {
    try {
        if (bksFile == null || password == null) return null;
        KeyStore clientKeyStore = KeyStore.getInstance("BKS");
        clientKeyStore.load(bksFile, password.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(clientKeyStore, password.toCharArray());
        return kmf.getKeyManagers();
    } catch (Exception e) {

    }
    return null;
}
 
Example 30
Project: lib-commons-httpclient   File: AuthSSLProtocolSocketFactory.java   View source code 5 votes vote down vote up
private static KeyManager[] createKeyManagers(final KeyStore keystore, final String password)
    throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException 
{
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }
    LOG.debug("Initializing key manager");
    KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
        KeyManagerFactory.getDefaultAlgorithm());
    kmfactory.init(keystore, password != null ? password.toCharArray(): null);
    return kmfactory.getKeyManagers(); 
}
 
Example 31
Project: aos-FileCoreLibrary   File: SSLContextUtils.java   View source code 5 votes vote down vote up
/**
 * Create and initialise sn SSLContext.
 * @param protocol the protocol used to instatiate the context
 * @param keyManagers the array of key managers, may be {@code null} but array entries must not be {@code null}
 * @param trustManagers the array of trust managers, may be {@code null} but array entries must not be {@code null}
 * @return the initialised context.
 * @throws java.io.IOException this is used to wrap any {@link java.security.GeneralSecurityException} that occurs
 */
public static SSLContext createSSLContext(String protocol, KeyManager[] keyManagers, TrustManager[] trustManagers)
    throws IOException {
    SSLContext ctx;
    try {
        ctx = SSLContext.getInstance(protocol);
        ctx.init(keyManagers, trustManagers, /*SecureRandom*/ null);
    } catch (GeneralSecurityException e) {
        IOException ioe = new IOException("Could not initialize SSL context");
        ioe.initCause(e);
        throw ioe;
    }
    return ctx;
}
 
Example 32
Project: rxjava2_retrofit2   File: HttpsUtils.java   View source code 5 votes vote down vote up
private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) {
    try {
        if (bksFile == null || password == null) return null;

        KeyStore clientKeyStore = KeyStore.getInstance("BKS");
        clientKeyStore.load(bksFile, password.toCharArray());
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(clientKeyStore, password.toCharArray());
        return keyManagerFactory.getKeyManagers();

    }  catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 33
Project: lighthouse   File: SSLContextBuilder.java   View source code 5 votes vote down vote up
protected void initSSLContext(
        final SSLContext sslcontext,
        final Collection<KeyManager> keyManagers,
        final Collection<TrustManager> trustManagers,
        final SecureRandom secureRandom) throws KeyManagementException {
    sslcontext.init(
            !keyManagers.isEmpty() ? keyManagers.toArray(new KeyManager[keyManagers.size()]) : null,
            !trustManagers.isEmpty() ? trustManagers.toArray(new TrustManager[trustManagers.size()]) : null,
            secureRandom);
}
 
Example 34
Project: alfresco-core   File: AlfrescoKeyStoreImpl.java   View source code 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public KeyManager[] createKeyManagers()
{
    KeyInfoManager keyInfoManager = null;

    try
    {
        keyInfoManager = getKeyInfoManager(getKeyMetaDataFileLocation());
        KeyStore ks = loadKeyStore(keyStoreParameters, keyInfoManager);

        logger.debug("Initializing key managers");
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        
        String keyStorePassword = keyInfoManager.getKeyStorePassword();
        kmfactory.init(ks, keyStorePassword != null ? keyStorePassword.toCharArray(): null);
        return kmfactory.getKeyManagers(); 
    }
    catch(Throwable e)
    {
        throw new AlfrescoRuntimeException("Unable to create key manager", e);
    }
    finally
    {
        if(keyInfoManager != null)
        {
            keyInfoManager.clear();
        }
    }
}
 
Example 35
Project: tomcat7   File: JSSESocketFactory.java   View source code 5 votes vote down vote up
@Override
public KeyManager[] getKeyManagers() throws Exception {
    String keystoreType = endpoint.getKeystoreType();
    if (keystoreType == null) {
        keystoreType = defaultKeystoreType;
    }

    String algorithm = endpoint.getAlgorithm();
    if (algorithm == null) {
        algorithm = KeyManagerFactory.getDefaultAlgorithm();
    }

    return getKeyManagers(keystoreType, endpoint.getKeystoreProvider(),
            algorithm, endpoint.getKeyAlias());
}
 
Example 36
Project: tomcat7   File: JSSESocketFactory.java   View source code 5 votes vote down vote up
/**
 * Gets the initialized key managers.
 */
protected KeyManager[] getKeyManagers(String keystoreType,
                                      String keystoreProvider,
                                      String algorithm,
                                      String keyAlias)
            throws Exception {

    KeyManager[] kms = null;

    String keystorePass = getKeystorePassword();

    KeyStore ks = getKeystore(keystoreType, keystoreProvider, keystorePass);
    if (keyAlias != null && !ks.isKeyEntry(keyAlias)) {
        throw new IOException(
                sm.getString("jsse.alias_no_key_entry", keyAlias));
    }

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
    String keyPass = endpoint.getKeyPass();
    if (keyPass == null) {
        keyPass = keystorePass;
    }
    kmf.init(ks, keyPass.toCharArray());

    kms = kmf.getKeyManagers();
    if (keyAlias != null) {
        String alias = keyAlias;
        if (JSSESocketFactory.defaultKeystoreType.equals(keystoreType)) {
            alias = alias.toLowerCase(Locale.ENGLISH);
        }
        for(int i=0; i<kms.length; i++) {
            kms[i] = new JSSEKeyManager((X509KeyManager)kms[i], alias);
        }
    }

    return kms;
}
 
Example 37
Project: tomcat7   File: TesterSupport.java   View source code 5 votes vote down vote up
protected static KeyManager[] getUser1KeyManagers() throws Exception {
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(
            KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(getKeyStore("org/apache/tomcat/util/net/user1.jks"),
            "changeit".toCharArray());
    return kmf.getKeyManagers();
}
 
Example 38
Project: MQTT-Essentials-A-Lightweight-IoT-Protocol   File: SecurityHelper.java   View source code 5 votes vote down vote up
public static SSLSocketFactory createSocketFactory(
	final String caCertificateFileName, 
	final String clientCertificateFileName, 
	final String clientKeyFileName) throws Exception
{
	// Creates a TLS socket factory with the given 
	// CA certificate file, client certificate, client key
	// In this case, we are working without a client key password
	final String clientKeyPassword = "";
	try
	{
		Security.addProvider(new BouncyCastleProvider());
		final KeyManager[] keyManagers = createKeyManagerFactory(clientCertificateFileName, clientKeyFileName, clientKeyPassword).getKeyManagers();
		final TrustManager[] trustManagers = createTrustManagerFactory(caCertificateFileName).getTrustManagers();
		
		// Create the TLS socket factory for the desired TLS version
		final SSLContext context = SSLContext.getInstance(TLS_VERSION);
		
		context.init(keyManagers, trustManagers, new SecureRandom());
		//context.init(keyManagers, trustManagers, null);

		return context.getSocketFactory();			
	}
	catch (Exception e)
	{
		throw new Exception("I cannot create the TLS socket factory.", e);
	}		
}
 
Example 39
Project: syndesis   File: ActiveMQUtil.java   View source code 5 votes vote down vote up
public static KeyManager[] createKeyManagers(String clientCertificate) throws GeneralSecurityException, IOException {
    final KeyStore clientKs = createKeyStore("amq-client", clientCertificate);

    // create Key Manager
    KeyManagerFactory kmFactory = KeyManagerFactory.getInstance("PKIX");
    kmFactory.init(clientKs, null);
    return kmFactory.getKeyManagers();
}
 
Example 40
Project: nifi-android-s2s   File: SiteToSiteRemoteCluster.java   View source code 5 votes vote down vote up
private KeyManager[] getKeyManagers() {
    if (keystoreFilename != null && keystorePassword != null && keystoreType != null) {
        try {
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            KeyStore keystore = KeyStore.getInstance(keystoreType);
            loadKeystore(keystore, keystoreFilename, keystorePassword);
            keyManagerFactory.init(keystore, keystorePassword.toCharArray());
            return keyManagerFactory.getKeyManagers();
        } catch (Exception e) {
            throw new IllegalStateException("Failed to load Keystore", e);
        }
    } else {
        return null;
    }
}