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: openjdk-jdk10   File: EmptyCertificateAuthorities.java   Source Code and License 9 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 2
Project: lazycat   File: NioEndpoint.java   Source Code and License 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 3
Project: incubator-servicecomb-java-chassis   File: KeyStoreUtil.java   Source Code and License 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 4
Project: mobile-store   File: LocalRepoKeyStore.java   Source Code and License 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 5
Project: drift   File: ApacheThriftMethodInvokerFactory.java   Source Code and License 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 6
Project: rxjava2_retrofit2   File: CustomHttpsTrust.java   Source Code and License 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 7
Project: rxjava2_retrofit2   File: CustomHttpsTrust.java   Source Code and License 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 8
Project: RoughWorld   File: WebInterfaceSSL.java   Source Code and License 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 9
Project: spur   File: SpurOptions.java   Source Code and License 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 10
Project: syndesis   File: ActiveMQUtilTest.java   Source Code and License 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 11
Project: wx-idk   File: HttpsRequestTools.java   Source Code and License 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 12
Project: apache-tomcat-7.0.73-with-comment   File: NioEndpoint.java   Source Code and License 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 13
Project: jdk8u-jdk   File: JSSEServer.java   Source Code and License 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 14
Project: openjdk-jdk10   File: JSSEServer.java   Source Code and License 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 15
Project: TrackMeIfYouCanChat   File: Registrar.java   Source Code and License 6 votes vote down vote up
public static SSLContext createSSLContext()
{
    try
    {
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream("A2KeyStore.jks"), "1234567890".toCharArray());

        // Create key manager
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
        keyManagerFactory.init(keyStore, "1234567890".toCharArray());
        KeyManager[] km = keyManagerFactory.getKeyManagers();

        // Create trust manager
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
        trustManagerFactory.init(keyStore);
        TrustManager[] tm = trustManagerFactory.getTrustManagers();

        // Initialize SSLContext
        SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(km, tm, null);

        return sslContext;
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }

    return null;
}
 
Example 16
Project: jetfuel   File: X509CertificateWithKey.java   Source Code and License 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 17
Project: GitHub   File: HttpsUtils.java   Source Code and License 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 18
Project: VBrowser-Android   File: NanoHTTPD.java   Source Code and License 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 19
Project: springboot-shiro-cas-mybatis   File: FileTrustStoreSslSocketFactory.java   Source Code and License 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 20
Project: springboot-shiro-cas-mybatis   File: FileTrustStoreSslSocketFactory.java   Source Code and License 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 21
Project: ultrasonic   File: SSLSocketFactory.java   Source Code and License 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 22
Project: java-buildpack-security-provider   File: FileWatchingX509ExtendedKeyManager.java   Source Code and License 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 23
Project: EvolvingNetLib   File: HttpsUtil.java   Source Code and License 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 24
Project: SuperHttp   File: HttpsUtils.java   Source Code and License 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 25
Project: lib-commons-httpclient   File: AuthSSLProtocolSocketFactory.java   Source Code and License 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 26
Project: aos-FileCoreLibrary   File: SSLContextUtils.java   Source Code and License 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 27
Project: rxjava2_retrofit2   File: HttpsUtils.java   Source Code and License 5 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 28
Project: rxjava2_retrofit2   File: HttpsUtils.java   Source Code and License 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 29
Project: lighthouse   File: SSLContextBuilder.java   Source Code and License 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 30
Project: alfresco-core   File: AuthSSLProtocolSocketFactory.java   Source Code and License 5 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 31
Project: alfresco-core   File: AlfrescoKeyStoreImpl.java   Source Code and License 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 32
Project: tomcat7   File: JSSESocketFactory.java   Source Code and License 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 33
Project: tomcat7   File: JSSESocketFactory.java   Source Code and License 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 34
Project: tomcat7   File: TesterSupport.java   Source Code and License 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 35
Project: syndesis   File: ActiveMQUtil.java   Source Code and License 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 36
Project: nifi-android-s2s   File: SiteToSiteRemoteCluster.java   Source Code and License 5 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 37
Project: nifi-android-s2s   File: SiteToSiteRemoteCluster.java   Source Code and License 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;
    }
}
 
Example 38
Project: iotplatform   File: MqttSslHandlerProvider.java   Source Code and License 5 votes vote down vote up
public SslHandler getSslHandler() {
    try {
        URL ksUrl = Resources.getResource(keyStoreFile);
        File ksFile = new File(ksUrl.toURI());
        URL tsUrl = Resources.getResource(keyStoreFile);
        File tsFile = new File(tsUrl.toURI());

        TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        KeyStore trustStore = KeyStore.getInstance(keyStoreType);
        trustStore.load(new FileInputStream(tsFile), keyStorePassword.toCharArray());
        tmFactory.init(trustStore);

        KeyStore ks = KeyStore.getInstance(keyStoreType);

        ks.load(new FileInputStream(ksFile), keyStorePassword.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, keyPassword.toCharArray());

        KeyManager[] km = kmf.getKeyManagers();
        TrustManager x509wrapped = getX509TrustManager(tmFactory);
        TrustManager[] tm = {x509wrapped};
        SSLContext sslContext = SSLContext.getInstance(TLS);
        sslContext.init(km, tm, null);
        SSLEngine sslEngine = sslContext.createSSLEngine();
        sslEngine.setUseClientMode(false);
        sslEngine.setNeedClientAuth(false);
        sslEngine.setWantClientAuth(true);
        sslEngine.setEnabledProtocols(sslEngine.getSupportedProtocols());
        sslEngine.setEnabledCipherSuites(sslEngine.getSupportedCipherSuites());
        sslEngine.setEnableSessionCreation(true);
        return new SslHandler(sslEngine);
    } catch (Exception e) {
        log.error("Unable to set up SSL context. Reason: " + e.getMessage(), e);
        throw new RuntimeException("Failed to get SSL handler", e);
    }
}
 
Example 39
Project: RISE-V2G   File: SecurityUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Sets the SSLContext of the TLSServer and TLSClient with the given keystore and truststore locations as
 * well as the password protecting the keystores/truststores.
 * 
 * @param keyStorePath The relative path and filename for the keystore
 * @param trustStorePath The relative path and filename for the truststore
 * @param keyStorePassword The password protecting the keystore
 */
public static void setSSLContext(
		String keyStorePath, 
		String trustStorePath,
		String keyStorePassword) {
    KeyStore keyStore = SecurityUtils.getKeyStore(keyStorePath, keyStorePassword);
    KeyStore trustStore = SecurityUtils.getKeyStore(trustStorePath, keyStorePassword);

	try {
		// Initialize a key manager factory with the keystore
	    KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
		keyFactory.init(keyStore, keyStorePassword.toCharArray());
	    KeyManager[] keyManagers = keyFactory.getKeyManagers();

	    // Initialize a trust manager factory with the truststore
	    TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());    
	    trustFactory.init(trustStore);
	    TrustManager[] trustManagers = trustFactory.getTrustManagers();

	    // Initialize an SSL context to use these managers and set as default
	    SSLContext sslContext = SSLContext.getInstance("TLS");
	    sslContext.init(keyManagers, trustManagers, null);
	    SSLContext.setDefault(sslContext); 
	} catch (NoSuchAlgorithmException | UnrecoverableKeyException | KeyStoreException | 
			KeyManagementException e) {
		getLogger().error(e.getClass().getSimpleName() + " occurred while trying to initialize SSL context");
	}    
}
 
Example 40
Project: lazycat   File: JSSESocketFactory.java   Source Code and License 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 41
Project: fresco_floodlight   File: OFChannelInitializer.java   Source Code and License 5 votes vote down vote up
@Override
protected void initChannel(Channel ch) throws Exception {
	ChannelPipeline pipeline = ch.pipeline();
	OFChannelHandler handler = new OFChannelHandler(
			switchManager,
			connectionListener,
			pipeline,
			debugCounters,
			timer,
			ofBitmaps,
			defaultFactory);

	if (keyStore != null && keyStorePassword != null) {
		try {
			/* Set up factories and stores. */
			TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
			KeyStore tmpKS = null;
			tmFactory.init(tmpKS);

			/* Use keystore/pass defined in properties file. */
			KeyStore ks = KeyStore.getInstance("JKS");
			ks.load(new FileInputStream(keyStore), keyStorePassword.toCharArray());

			KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
			kmf.init(ks, keyStorePassword.toCharArray());

			KeyManager[] km = kmf.getKeyManagers();
			TrustManager[] tm = tmFactory.getTrustManagers();

			/* Set up SSL prereqs for Netty. */
			SSLContext sslContext = SSLContext.getInstance("TLS");
			sslContext.init(km, tm, null);
			SSLEngine sslEngine = sslContext.createSSLEngine();

			/* We are the server and we will create secure sessions. */
			sslEngine.setUseClientMode(false);
			sslEngine.setEnableSessionCreation(true);

			/* These are redundant (default), but for clarity... */
			sslEngine.setEnabledProtocols(sslEngine.getSupportedProtocols()); 
			sslEngine.setEnabledCipherSuites(sslEngine.getSupportedCipherSuites());
			
			/* First, decrypt w/handler+engine; then, proceed with rest of handlers. */
			pipeline.addLast(PipelineHandler.SSL_TLS_ENCODER_DECODER, new SslHandler(sslEngine));
			log.info("SSL OpenFlow socket initialized and handler ready for switch.");
		} catch (Exception e) { /* There are lots of possible exceptions to catch, so this should get them all. */
			log.error("Exception initializing SSL OpenFlow socket: {}", e.getMessage());
			throw e; /* If we wanted secure but didn't get it, we should bail. */
		}
	}
	
	pipeline.addLast(PipelineHandler.OF_MESSAGE_DECODER,
			new OFMessageDecoder());
	pipeline.addLast(PipelineHandler.OF_MESSAGE_ENCODER,
			new OFMessageEncoder());
	pipeline.addLast(PipelineHandler.MAIN_IDLE,
			new IdleStateHandler(PipelineIdleReadTimeout.MAIN,
					PipelineIdleWriteTimeout.MAIN,
					0));
	pipeline.addLast(PipelineHandler.READ_TIMEOUT, new ReadTimeoutHandler(30));
	pipeline.addLast(PipelineHandler.CHANNEL_HANDSHAKE_TIMEOUT,
			new HandshakeTimeoutHandler(
					handler,
					timer,
					PipelineHandshakeTimeout.CHANNEL));

	pipeline.addLast(PipelineHandler.CHANNEL_HANDLER, handler);
}
 
Example 42
Project: java-buildpack-security-provider   File: CloudFoundryContainerKeyManagerFactoryTest.java   Source Code and License 5 votes vote down vote up
@Test
public void defaultKeyManagerForNullPrivateKeyLocation() throws NoSuchProviderException, NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException, UnrecoverableKeyException {
    CloudFoundryContainerKeyManagerFactory.SunX509 factory = new CloudFoundryContainerKeyManagerFactory.SunX509(
        Paths.get("src/test/resources/client-certificates-1.pem"),
        null);
    factory.engineInit(getKeyStore(), new char[0]);


    KeyManager keyManager = factory.engineGetKeyManagers()[0];
    assertThat(keyManager).isInstanceOf(DelegatingX509ExtendedKeyManager.class);
    assertThat(((DelegatingX509ExtendedKeyManager) keyManager).size()).isEqualTo(1);
}
 
Example 43
Project: SmartChart   File: HttpsUtils.java   Source Code and License 5 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 44
Project: lams   File: SSLSocketFactory.java   Source Code and License 5 votes vote down vote up
private static SSLContext createSSLContext(
        String algorithm,
        final KeyStore keystore,
        final String keystorePassword,
        final KeyStore truststore,
        final SecureRandom random,
        final TrustStrategy trustStrategy)
            throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {
    if (algorithm == null) {
        algorithm = TLS;
    }
    KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
            KeyManagerFactory.getDefaultAlgorithm());
    kmfactory.init(keystore, keystorePassword != null ? keystorePassword.toCharArray(): null);
    KeyManager[] keymanagers =  kmfactory.getKeyManagers();
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(
            TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(truststore);
    TrustManager[] trustmanagers = tmfactory.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 45
Project: lams   File: JSSESocketFactory.java   Source Code and License 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);
    kmf.init(ks, keystorePass.toCharArray());

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

    return kms;
}
 
Example 46
Project: lams   File: JSSESocketFactory.java   Source Code and License 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;

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

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
    kmf.init(ks, listener.getSslKeyStorePass().toCharArray());

    kms = kmf.getKeyManagers();
    if (keyAlias != null) {
        if ("JKS".equals(keystoreType)) {
            keyAlias = keyAlias.toLowerCase();
        }
        for(int i=0; i<kms.length; i++) {
            kms[i] = new JSSEKeyManager((X509KeyManager)kms[i], keyAlias);
        }
    }

    return kms;
}
 
Example 47
Project: lams   File: Undertow.java   Source Code and License 5 votes vote down vote up
private ListenerConfig(final ListenerType type, final int port, final String host, KeyManager[] keyManagers, TrustManager[] trustManagers) {
    this.type = type;
    this.port = port;
    this.host = host;
    this.keyManagers = keyManagers;
    this.trustManagers = trustManagers;
    this.sslContext = null;
}
 
Example 48
Project: java-buildpack-security-provider   File: CloudFoundryContainerKeyManagerFactoryTest.java   Source Code and License 5 votes vote down vote up
@Test
public void defaultKeyManagerForNullCertificatesLocation() throws NoSuchProviderException, NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException,
    UnrecoverableKeyException {
    CloudFoundryContainerKeyManagerFactory.SunX509 factory = new CloudFoundryContainerKeyManagerFactory.SunX509(
        null,
        Paths.get("src/test/resources/client-private-key-1.pem"));
    factory.engineInit(getKeyStore(), new char[0]);


    KeyManager keyManager = factory.engineGetKeyManagers()[0];
    assertThat(keyManager).isInstanceOf(DelegatingX509ExtendedKeyManager.class);
    assertThat(((DelegatingX509ExtendedKeyManager) keyManager).size()).isEqualTo(1);
}
 
Example 49
Project: cyberduck   File: DefaultX509KeyManager.java   Source Code and License 5 votes vote down vote up
private synchronized javax.net.ssl.X509KeyManager getKeystore() throws IOException {
    try {
        if(null == _manager) {
            // Get the key manager factory for the default algorithm.
            final KeyManagerFactory factory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            final KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
            // Load default key store
            store.load(null);
            // Load default key manager factory using key store
            factory.init(store, null);
            for(KeyManager m : factory.getKeyManagers()) {
                if(m instanceof javax.net.ssl.X509KeyManager) {
                    // Get the first X509KeyManager in the list
                    _manager = (javax.net.ssl.X509KeyManager) m;
                    break;
                }
            }
            if(null == _manager) {
                throw new NoSuchAlgorithmException(String.format("The default algorithm %s did not produce a X.509 key manager",
                        KeyManagerFactory.getDefaultAlgorithm()));
            }
        }
        return _manager;
    }
    catch(CertificateException | UnrecoverableKeyException | KeyStoreException | NoSuchAlgorithmException e) {
        log.error(String.format("Initialization of key store failed. %s", e.getMessage()));
        throw new IOException(e);
    }
}
 
Example 50
Project: opentest   File: HttpRequest.java   Source Code and License 5 votes vote down vote up
private CloseableHttpClient createHttpClient(boolean ignoreCert) {
    try {
        RequestConfig requestConfig = RequestConfig.custom()
                .setCookieSpec(CookieSpecs.STANDARD)
                .build();

        CloseableHttpClient client;

        if (ignoreCert) {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(new KeyManager[0], new TrustManager[]{new NoopTrustManager()}, new SecureRandom());
            SSLContext.setDefault(sslContext);

            SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
                    sslContext, NoopHostnameVerifier.INSTANCE);
            client = HttpClients.custom()
                    .disableRedirectHandling()
                    .setDefaultRequestConfig(requestConfig)
                    .setSSLSocketFactory(sslSocketFactory)
                    .build();
        } else {
            client = HttpClientBuilder.create()
                    .disableRedirectHandling()
                    .setDefaultRequestConfig(requestConfig)
                    .build();
        }

        return client;
    } catch (Throwable ex) {
        throw new RuntimeException(String.format(
                "Failed to create http client (ignoreCert = %s)",
                ignoreCert), ex);
    }
}
 
Example 51
Project: Xndroid   File: SHelper.java   Source Code and License 5 votes vote down vote up
public static void enableAnySSL() {
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[]{new DefaultTrustManager()}, new SecureRandom());
        SSLContext.setDefault(ctx);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
 
Example 52
Project: M3U8_Video_demo   File: NanoHTTPD.java   Source Code and License 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 53
Project: monarch   File: SocketCreator.java   Source Code and License 5 votes vote down vote up
/**
 * Creates & configures the SSLContext when SSL is enabled.
 * 
 * @return new SSLContext configured using the given protocols & properties
 *
 * @throws GeneralSecurityException if security information can not be found
 * @throws IOException if information can not be loaded
 */
private SSLContext createAndConfigureSSLContext() throws GeneralSecurityException, IOException {

  SSLContext newSSLContext = getSSLContextInstance();
  KeyManager[] keyManagers = getKeyManagers();
  TrustManager[] trustManagers = getTrustManagers();

  newSSLContext.init(keyManagers, trustManagers, null /* use the default secure random */);
  return newSSLContext;
}
 
Example 54
Project: li-android-sdk-core   File: LiRestv2ClientTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testValidateResponse() throws Exception {
    context = Mockito.mock(Activity.class);
    PowerMockito.mockStatic(LiClientManager.class);
    LiClientManager liClientManager = PowerMockito.mock(LiClientManager.class);

    PowerMockito.mockStatic(SSLContext.class);
    SSLContext sslContext = PowerMockito.mock(SSLContext.class);
    when(sslContext.getInstance("SSL")).thenReturn(sslContext);
    Mockito.doNothing().when(sslContext).init(isA(KeyManager[].class), isA(TrustManager[].class), isA(SecureRandom.class));
    SSLSocketFactory socketFactory = mock(SSLSocketFactory.class);
    when(sslContext.getSocketFactory()).thenReturn(socketFactory);

    PowerMockito.mockStatic(Platform.class);
    Platform platform = PowerMockito.mock(Platform.class);
    X509TrustManager trustManager = mock(X509TrustManager.class);
    when(platform.trustManager(socketFactory)).thenReturn(trustManager);
    BDDMockito.given(Platform.get()).willReturn(platform);

    BDDMockito.given(SSLContext.getInstance("SSL")).willReturn(sslContext);

    LiRestv2Client liRestv2Client = LiRestv2Client.getInstance();
    final LiBaseResponse liBaseResponse = mock(LiBaseResponse.class);
    when(liBaseResponse.getHttpCode()).thenReturn(200);
    LiRestv2Client liRestv2ClientSpy = spy(LiRestv2Client.class);
    doReturn(liBaseResponse).when(liRestv2ClientSpy).processSync(isA(LiBaseRestRequest.class));

    LiRestV2Request liBaseRestRequest = new LiRestV2Request(context, liql, "message");
    liBaseRestRequest.addQueryParam("test");

    LiBaseResponse liBaseResponse1 = liRestv2ClientSpy.processSync(liBaseRestRequest);

    Assert.assertEquals(200, liBaseResponse1.getHttpCode());
    PowerMockito.verifyStatic();
}
 
Example 55
Project: apache-tomcat-7.0.73-with-comment   File: JSSESocketFactory.java   Source Code and License 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 56
Project: apache-tomcat-7.0.73-with-comment   File: JSSESocketFactory.java   Source Code and License 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 57
Project: apache-tomcat-7.0.73-with-comment   File: TesterSupport.java   Source Code and License 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 58
Project: TPlayer   File: HttpsUtils.java   Source Code and License 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 59
Project: FastLib   File: SSLUtil.java   Source Code and License 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) {
        Log.e("ssl", e.getMessage());
    }
    return null;
}
 
Example 60
Project: cli-java   File: AocClientOptionManager.java   Source Code and License 5 votes vote down vote up
@Override
    protected void createConnectionOptions(ClientOptions clientOptions) {
        // see the link for source of inspiration. NOTE: the TrustingTrustManager is never unset!
        // http://activemq.2283324.n4.nabble.com/Configure-activemq-client-to-trust-any-SSL-certificate-from-the-broker-without-verifying-it-td4733309.html
        if (clientOptions.getOption(ClientOptions.CON_SSL_TRUST_ALL).hasParsedValue()) {
            try {
                SSLContext ctx = SSLContext.getInstance("TLS");
                ctx.init(new KeyManager[0], new TrustManager[]{new TrustingTrustManager()}, null);
                SSLContext.setDefault(ctx);
            } catch (NoSuchAlgorithmException | KeyManagementException e) {
                throw new RuntimeException("Could not set up the all-trusting TrustManager", e);
            }
        }

        // Configure SSL options, which in case of activemq-client are set as Java properties
        // http://activemq.apache.org/how-do-i-use-ssl.html
        // https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html#CustomizingStores

        if (clientOptions.getOption(ClientOptions.CON_SSL_KEYSTORE_LOC).hasParsedValue()) {
            System.setProperty("javax.net.ssl.keyStore", relativize(clientOptions.getOption(ClientOptions.CON_SSL_KEYSTORE_LOC).getValue()));
        }
        if (clientOptions.getOption(ClientOptions.CON_SSL_KEYSTORE_PASS).hasParsedValue()) {
            System.setProperty("javax.net.ssl.keyStorePassword", clientOptions.getOption(ClientOptions.CON_SSL_KEYSTORE_PASS).getValue());
        }
//        System.setProperty("javax.net.ssl.keyStorePassword", "secureexample");
        if (clientOptions.getOption(ClientOptions.CON_SSL_TRUSTSTORE_LOC).hasParsedValue()) {
            System.setProperty("javax.net.ssl.trustStore", relativize(clientOptions.getOption(ClientOptions.CON_SSL_TRUSTSTORE_LOC).getValue()));
        }
        if (clientOptions.getOption(ClientOptions.CON_SSL_TRUSTSTORE_PASS).hasParsedValue()) {
            System.setProperty("javax.net.ssl.trustStorePassword", clientOptions.getOption(ClientOptions.CON_SSL_TRUSTSTORE_PASS).getValue());
        }
        if (clientOptions.getOption(ClientOptions.CON_SSL_STORE_TYPE).hasParsedValue()) {
            System.setProperty("javax.net.ssl.keyStoreType", clientOptions.getOption(ClientOptions.CON_SSL_STORE_TYPE).getValue());
            System.setProperty("javax.net.ssl.trustStoreType", clientOptions.getOption(ClientOptions.CON_SSL_STORE_TYPE).getValue());
        }

        super.createConnectionOptions(clientOptions);
    }