Java Code Examples for javax.net.ssl.TrustManagerFactory

The following examples show how to use javax.net.ssl.TrustManagerFactory. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: carina   Source File: SSLContextBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create an SSLContext with mutual TLS authentication enabled; returns null if the
 * tlsConfigDirectory was not found.
 *
 * @return SSLContext
 */
public SSLContext createSSLContext() {
    if (tlsConfigDirectory == null) {
        return null;
    }

    try {
        // Get the client's public/private key pair
        KeyManagerFactory kmf = null;
        if (this.isClientAuthEnabled) {
            kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(createPrivateKeyStore(), readKeyStorePassword(tlsConfigDirectory));
        }
        // Get the client's trustStore for what server certificates the client will trust
        TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustFactory.init(createTrustStore());

        // Create SSL context with the client's keyStore and trustStore
        SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init((this.isClientAuthEnabled) ? kmf.getKeyManagers() : null, trustFactory.getTrustManagers(), null);
        return sslContext;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 2
Source Project: directory-ldap-api   Source File: LdapConnectionConfig.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sets the default trust manager based on the SunX509 trustManagement algorithm
 * 
 * We use a non-verification Trust Manager    
 **/
private void setDefaultTrustManager()
{
    String defaultAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    
    try
    {
        TrustManagerFactory tmf = TrustManagerFactory.getInstance( defaultAlgorithm );
        tmf.init( ( KeyStore ) null );
        trustManagers = tmf.getTrustManagers();
    }
    catch ( KeyStoreException kse )
    {
        LOG.error( I18n.err( I18n.ERR_04172_KEYSTORE_INIT_FAILURE ) );
        throw new RuntimeException( kse.getMessage(), kse );
    }
    catch ( NoSuchAlgorithmException nsae )
    {
        LOG.error( I18n.err( I18n.ERR_04173_ALGORITHM_NOT_FOUND, defaultAlgorithm ) );
        throw new RuntimeException( nsae.getMessage(), nsae );
    }
}
 
Example 3
Source Project: pulsar   Source File: SecurityUtility.java    License: Apache License 2.0 6 votes vote down vote up
private static TrustManager[] setupTrustCerts(KeyStoreHolder ksh, boolean allowInsecureConnection,
        Certificate[] trustCertficates) throws NoSuchAlgorithmException, KeyStoreException {
    TrustManager[] trustManagers;
    if (allowInsecureConnection) {
        trustManagers = InsecureTrustManagerFactory.INSTANCE.getTrustManagers();
    } else {
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

        if (trustCertficates == null || trustCertficates.length == 0) {
            tmf.init((KeyStore) null);
        } else {
            for (int i = 0; i < trustCertficates.length; i++) {
                ksh.setCertificate("trust" + i, trustCertficates[i]);
            }
            tmf.init(ksh.getKeyStore());
        }

        trustManagers = tmf.getTrustManagers();
    }
    return trustManagers;
}
 
Example 4
Source Project: tomcatsrc   Source File: JSSESocketFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public TrustManager[] getTrustManagers() throws Exception {
    String truststoreType = endpoint.getTruststoreType();
    if (truststoreType == null) {
        truststoreType = System.getProperty("javax.net.ssl.trustStoreType");
    }
    if (truststoreType == null) {
        truststoreType = endpoint.getKeystoreType();
    }
    if (truststoreType == null) {
        truststoreType = defaultKeystoreType;
    }

    String algorithm = endpoint.getTruststoreAlgorithm();
    if (algorithm == null) {
        algorithm = TrustManagerFactory.getDefaultAlgorithm();
    }

    return getTrustManagers(truststoreType, endpoint.getKeystoreProvider(),
            algorithm);
}
 
Example 5
Source Project: pandroid   Source File: PandroidModule.java    License: Apache License 2.0 6 votes vote down vote up
protected X509TrustManager getTrustManager() {
    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
                TrustManagerFactory.getDefaultAlgorithm());

        trustManagerFactory.init((KeyStore) null);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
            throw new IllegalStateException("Unexpected default trust managers:"
                    + Arrays.toString(trustManagers));
        }
        return (X509TrustManager) trustManagers[0];
    } catch (Exception e) {
        return null;
    }
}
 
Example 6
Source Project: cxf   Source File: JAXRS20HttpsBookTest.java    License: Apache License 2.0 6 votes vote down vote up
private SSLContext createSSLContext() throws Exception {
    TLSClientParameters tlsParams = new TLSClientParameters();

    try (InputStream keystore = ClassLoaderUtils.getResourceAsStream("keys/Truststore.jks", this.getClass())) {
        KeyStore trustStore = loadStore(keystore, "password");

        TrustManagerFactory tmf =
            TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);
        tlsParams.setTrustManagers(tmf.getTrustManagers());
    }

    try (InputStream keystore = ClassLoaderUtils.getResourceAsStream("keys/Morpit.jks", this.getClass())) {
        KeyStore keyStore = loadStore(keystore, "password");

        KeyManagerFactory kmf =
            KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(keyStore, "password".toCharArray());
        tlsParams.setKeyManagers(kmf.getKeyManagers());
    }

    return SSLUtils.getSSLContext(tlsParams);
}
 
Example 7
X509TrustManager getTrustManager(KeyStore ks) {
	try {
		TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
		tmf.init(ks);
		for (TrustManager t : tmf.getTrustManagers()) {
			if (t instanceof X509TrustManager) {
				return (X509TrustManager)t;
			}
		}
	} catch (Exception e) {
		// Here, we are covering up errors. It might be more useful
		// however to throw them out of the constructor so the
		// embedding app knows something went wrong.
		LOGGER.log(Level.SEVERE, "getTrustManager(" + ks + ")", e);
	}
	return null;
}
 
Example 8
Source Project: iaf   Source File: AuthSSLProtocolSocketFactory.java    License: Apache License 2.0 6 votes vote down vote up
private static TrustManager[] createTrustManagers(final KeyStore keystore, String algorithm)
    throws KeyStoreException, NoSuchAlgorithmException
{ 
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }
    log.debug("Initializing trust manager");
    if (StringUtils.isEmpty(algorithm)) {
    	algorithm=TrustManagerFactory.getDefaultAlgorithm();
    	log.debug("using default TrustManager algorithm ["+algorithm+"]");
    } else {
    	log.debug("using configured TrustManager algorithm ["+algorithm+"]");
    }
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(algorithm);
    tmfactory.init(keystore);
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    return trustmanagers; 
}
 
Example 9
Source Project: netty-4.1.22   Source File: SslContext.java    License: Apache License 2.0 6 votes vote down vote up
static TrustManagerFactory buildTrustManagerFactory(
        X509Certificate[] certCollection, TrustManagerFactory trustManagerFactory)
        throws NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException {
    final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(null, null);

    int i = 1;
    for (X509Certificate cert: certCollection) {
        String alias = Integer.toString(i);
        ks.setCertificateEntry(alias, cert);
        i++;
    }

    // Set up trust manager factory to use our key store.
    if (trustManagerFactory == null) {
        trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    }
    trustManagerFactory.init(ks);

    return trustManagerFactory;
}
 
Example 10
Source Project: Chronicle-Network   Source File: SSLContextLoader.java    License: Apache License 2.0 6 votes vote down vote up
@NotNull
static SSLContext getInitialisedContext() throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException, KeyManagementException {
    final SSLContext context = SSLContext.getInstance("TLS");
    KeyManagerFactory kmf =
            KeyManagerFactory.getInstance("SunX509");
    final KeyStore keyStore = KeyStore.getInstance("JKS");
    final char[] password = "password".toCharArray();
    keyStore.load(new FileInputStream(KEYSTORE_FILE), password);
    kmf.init(keyStore, password);

    final KeyStore trustStore = KeyStore.getInstance("JKS");
    trustStore.load(new FileInputStream(KEYSTORE_FILE), password);

    TrustManagerFactory tmf =
            TrustManagerFactory.getInstance("SunX509");
    tmf.init(trustStore);
    context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
    return context;
}
 
Example 11
Source Project: bouncr   Source File: BouncrSSLSocketFactory.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public BouncrSSLSocketFactory() {
    try {
        SSLContext ctx = SSLContext.getInstance("TLSv1.2");
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        KeyStore trustStore = KeyStore.getInstance("JKS");

        try (InputStream in = new FileInputStream(keyStoreInfo.get().getTruststorePath())) {
            trustStore.load(in, keyStoreInfo.get().getTruststorePassword().toCharArray());
        }
        tmf.init(trustStore);
        ctx.init(null, tmf.getTrustManagers(), SecureRandom.getInstance("SHA1PRNG"));
        delegate = ctx.getSocketFactory();
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example 12
Source Project: presto   Source File: TestInsecureQueryRunner.java    License: Apache License 2.0 6 votes vote down vote up
private SSLContext buildTestSslContext()
        throws Exception
{
    // Load self-signed certificate
    char[] serverKeyStorePassword = "insecure-ssl-test".toCharArray();
    KeyStore serverKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    try (InputStream in = getResource(getClass(), "/insecure-ssl-test.jks").openStream()) {
        serverKeyStore.load(in, serverKeyStorePassword);
    }

    String kmfAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(kmfAlgorithm);
    kmf.init(serverKeyStore, serverKeyStorePassword);

    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(kmfAlgorithm);
    trustManagerFactory.init(serverKeyStore);
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(kmf.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
    return sslContext;
}
 
Example 13
Source Project: cwac-netsecurity   Source File: MemorizingTrustManager.java    License: Apache License 2.0 6 votes vote down vote up
private void init() throws Exception {
  transientKeyStore=KeyStore.getInstance(storeType);
  transientKeyStore.load(null, null);

  TrustManagerFactory tmf=TrustManagerFactory.getInstance("X509");

  tmf.init(transientKeyStore);
  transientTrustManager=findX509TrustManager(tmf);

  keyStore=KeyStore.getInstance(storeType);

  if (store.exists()) {
    keyStore.load(new FileInputStream(store), storePassword);
  }
  else {
    keyStore.load(null, storePassword);
  }

  tmf=TrustManagerFactory.getInstance("X509");
  tmf.init(keyStore);
  storeTrustManager=findX509TrustManager(tmf);
}
 
Example 14
private static TrustManagerFactory createTrustManagerFactory(
	final String caCertificateFileName) 
	throws CertificateException, NoSuchAlgorithmException, IOException, KeyStoreException 
{
	// Creates a trust manager factory
	// Load CA certificate
	final X509Certificate caCertificate = (X509Certificate) createX509CertificateFromFile(caCertificateFileName);
	// CA certificate is used to authenticate server
	final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); 
	keyStore.load(null, null);
	keyStore.setCertificateEntry("ca-certificate", caCertificate);
	final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
	trustManagerFactory.init(keyStore);

	return trustManagerFactory;
}
 
Example 15
Source Project: elexis-3-core   Source File: SSLStoreService.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void addTrustStore(KeyStore keyStore){
	try {
		TrustManagerFactory factory =
			TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
		factory.init(keyStore);
		TrustManager[] managers = factory.getTrustManagers();
		for (TrustManager trustManager : managers) {
			if (trustManager instanceof X509TrustManager) {
				compositeTrustManager.addTrustManager((X509TrustManager) trustManager);
			}
		}
	} catch (NoSuchAlgorithmException | KeyStoreException e) {
		LoggerFactory.getLogger(getClass()).error("Could not add trust store", e);
	}
}
 
Example 16
Source Project: ditto   Source File: DittoTrustManagerFactory.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private DittoTrustManagerFactory(final TrustManagerFactory delegate, final String hostname) {
    super(new TrustManagerFactorySpi() {
        @Override
        protected void engineInit(KeyStore keyStore) throws KeyStoreException {
            delegate.init(keyStore);
        }

        @Override
        protected void engineInit(ManagerFactoryParameters managerFactoryParameters) throws
                InvalidAlgorithmParameterException {
            delegate.init(managerFactoryParameters);
        }

        @Override
        protected TrustManager[] engineGetTrustManagers() {
            return DittoTrustManager.wrapTrustManagers(delegate.getTrustManagers(), hostname);
        }
    }, delegate.getProvider(), delegate.getAlgorithm());
}
 
Example 17
Source Project: grpc-java   Source File: TestUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates an SSLSocketFactory which contains {@code certChainFile} as its only root certificate.
 */
public static SSLSocketFactory newSslSocketFactoryForCa(Provider provider,
                                                        File certChainFile) throws Exception {
  KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  ks.load(null, null);
  CertificateFactory cf = CertificateFactory.getInstance("X.509");
  BufferedInputStream in = new BufferedInputStream(new FileInputStream(certChainFile));
  try {
    X509Certificate cert = (X509Certificate) cf.generateCertificate(in);
    X500Principal principal = cert.getSubjectX500Principal();
    ks.setCertificateEntry(principal.getName("RFC2253"), cert);
  } finally {
    in.close();
  }

  // Set up trust manager factory to use our key store.
  TrustManagerFactory trustManagerFactory =
      TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  trustManagerFactory.init(ks);
  SSLContext context = SSLContext.getInstance("TLS", provider);
  context.init(null, trustManagerFactory.getTrustManagers(), null);
  return context.getSocketFactory();
}
 
Example 18
private static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManager[] keyManagers) throws IOException {
    final SSLServerSocketFactory factory;
    try {
        final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(loadedKeyStore);

        final SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagers, trustManagerFactory.getTrustManagers(), null);

        factory = sslContext.getServerSocketFactory();
    } catch (Exception e) {
        // simplify exception handling
        throw new IOException(e.getMessage());
    }
    return factory;
}
 
Example 19
Source Project: jmqtt   Source File: NettySslHandler.java    License: Apache License 2.0 6 votes vote down vote up
private static SslContext createSSLContext(boolean useClientCA, String sslKeyStoreType, String sslKeyFilePath, String sslManagerPwd, String sslStorePwd) {
    try {
        InputStream ksInputStream = new FileInputStream(sslKeyFilePath);
        KeyStore ks = KeyStore.getInstance(sslKeyStoreType);
        ks.load(ksInputStream, sslStorePwd.toCharArray());


        final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, sslManagerPwd.toCharArray());
        SslContextBuilder contextBuilder = SslContextBuilder.forServer(kmf);

        // whether need client CA(two-way authentication)
        if (useClientCA) {
            contextBuilder.clientAuth(ClientAuth.REQUIRE);
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(ks);
            contextBuilder.trustManager(tmf);
        }
        return contextBuilder.sslProvider(SslProvider.valueOf("JDK")).build();
    } catch (Exception ex) {
        log.error("Create ssl context failure.cause={}", ex);
        return null;
    }
}
 
Example 20
Source Project: linstor-server   Source File: SslTcpCommons.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static TrustManager[] createTrustManagers(
    final String file,
    final char[] trustStorePasswd,
    final String trustStoreType,
    final String trustManagerFactoryAlgorithm
)
    throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException
{
    KeyStore trustStore;
    try
    {
        trustStore = loadStore(file, trustStoreType, trustStorePasswd);
    }
    catch (FileNotFoundException fileNotFoundExc)
    {
        trustStore = null; // no trustStore given. SslEngine can handle null here
    }
    TrustManagerFactory trustMgrFactory = TrustManagerFactory.getInstance(trustManagerFactoryAlgorithm);
    trustMgrFactory.init(trustStore);
    return trustMgrFactory.getTrustManagers();
}
 
Example 21
Source Project: an2linuxclient   Source File: TlsHelper.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static SSLContext getNotificationTlsContext(Context c, Certificate serverCert){
    try {
        SSLContext tlsContext = SSLContext.getInstance(TLS_VERSIONS[0]);

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setKeyEntry("key", RsaHelper.getPrivateKey(c), "".toCharArray(),
                new Certificate[]{TlsHelper.getCertificate(c)});
        keyStore.setCertificateEntry("serverCert", serverCert);

        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, "".toCharArray());

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);

        tlsContext.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);
        return tlsContext;
    } catch (Exception e){
        Log.e("TlsHelper", "getNotificationTlsContext");
        Log.e("StackTrace", Log.getStackTraceString(e));
        return null;
    }
}
 
Example 22
Source Project: DeviceConnect-Android   Source File: DConnectWebService.java    License: MIT License 5 votes vote down vote up
/**
 * SSLServerSocketFactory を作成します.
 *
 * @param keyStore キーストア
 * @param password パスワード
 * @return SSLServerSocketFactoryのインスタンス
 * @throws GeneralSecurityException SSLServerSocketFactoryの作成に失敗した場合に発生
 */
private SSLServerSocketFactory createSSLServerSocketFactory(final KeyStore keyStore, final String password) throws GeneralSecurityException {
    SSLContext sslContext = SSLContext.getInstance("TLS");
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, password.toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
    return sslContext.getServerSocketFactory();
}
 
Example 23
Source Project: linstor-server   Source File: SslTcpCommons.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static TrustManager[] createTrustManagers(
    final String file,
    final char[] keyStorePasswd
)
    throws KeyStoreException, FileNotFoundException, NoSuchAlgorithmException, IOException, CertificateException
{
    return createTrustManagers(
        file, keyStorePasswd,
        SslTcpConstants.TRUST_STORE_DEFAULT_TYPE, TrustManagerFactory.getDefaultAlgorithm()
    );
}
 
Example 24
Source Project: ranger   Source File: NiFiRegistryConnectionMgr.java    License: Apache License 2.0 5 votes vote down vote up
private static SSLContext createSslContext(
        final String keystore, final char[] keystorePasswd, final String keystoreType,
        final String truststore, final char[] truststorePasswd, final String truststoreType,
        final String protocol)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException, KeyManagementException {

    // prepare the keystore
    final KeyStore keyStore = KeyStore.getInstance(keystoreType);
    try (final InputStream keyStoreStream = new FileInputStream(keystore)) {
        keyStore.load(keyStoreStream, keystorePasswd);
    }
    final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, keystorePasswd);

    // prepare the truststore
    final KeyStore trustStore = KeyStore.getInstance(truststoreType);
    try (final InputStream trustStoreStream = new FileInputStream(truststore)) {
        trustStore.load(trustStoreStream, truststorePasswd);
    }
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);

    // initialize the ssl context
    final SSLContext sslContext = SSLContext.getInstance(protocol);
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
    return sslContext;
}
 
Example 25
Source Project: joyrpc   Source File: SslContextManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 决定是否信任对方的证书
 *
 * @param url
 * @return
 * @throws Exception
 */
protected static TrustManagerFactory getTrustManagerFactory(final URL url) throws Exception {
    String caPath = url.getString(SSL_CA_PATH);
    if (isEmpty(caPath)) {
        return null;
    }
    TrustManagerFactory tf = TrustManagerFactory.getInstance(url.getString(SSL_CERTIFICATE));
    KeyStore tks = getKeyStore(caPath, url.getString(SSL_PASSWORD), url.getString(SSL_KEYSTORE));
    tf.init(tks);
    return tf;
}
 
Example 26
Source Project: ts-reaktive   Source File: SSLFactory.java    License: MIT License 5 votes vote down vote up
/**
 * Create an SSL context based on a KeyStore
 * 
 * @param ks A keystore with a private key and certificate chain.
 * @param password the password for the keystore.
 */
public static SSLContext createSSLContext(KeyStore ks, char[] password) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException, CertificateException, UnrecoverableKeyException {
    final SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, password);
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(ks);
    sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), SecureRandom.getInstance("SHA1PRNG"));
    return sslContext;
}
 
Example 27
Source Project: kylin   Source File: DefaultX509TrustManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Constructor for DefaultX509TrustManager.
 * 
 */
public DefaultX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException {
    super();

    TrustManagerFactory factory = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    factory.init(keystore);

    TrustManager[] trustmanagers = factory.getTrustManagers();

    if (trustmanagers.length == 0) {
        throw new NoSuchAlgorithmException("SunX509 trust manager not supported");
    }

    this.standardTrustManager = (X509TrustManager) trustmanagers[0];
}
 
Example 28
Source Project: http4e   Source File: EasyX509TrustManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Constructor for EasyX509TrustManager.
 */
public EasyX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException {
    super();
    TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    factory.init(keystore);
    TrustManager[] trustmanagers = factory.getTrustManagers();
    if (trustmanagers.length == 0) {
        throw new NoSuchAlgorithmException("no trust manager found");
    }
    this.standardTrustManager = (X509TrustManager)trustmanagers[0];
}
 
Example 29
Source Project: couchbase-lite-java   Source File: AbstractCBLWebSocket.java    License: Apache License 2.0 5 votes vote down vote up
private X509TrustManager trustManagerForCertificates(InputStream in) throws GeneralSecurityException {
    final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    final Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in);
    if (certificates.isEmpty()) {
        throw new IllegalArgumentException("expected non-empty set of trusted certificates");
    }

    // Put the certificates a key store.
    final char[] password = "umwxnikwxx".toCharArray(); // Any password will work.
    final KeyStore keyStore = newEmptyKeyStore(password);
    int index = 0;
    for (Certificate certificate : certificates) {
        final String certificateAlias = Integer.toString(index++);
        keyStore.setCertificateEntry(certificateAlias, certificate);
    }

    // Use it to build an X509 trust manager.
    final KeyManagerFactory keyManagerFactory
        = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, password);
    final TrustManagerFactory trustManagerFactory
        = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    final TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
    if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
        throw new IllegalStateException("Unexpected default trust managers:"
            + Arrays.toString(trustManagers));
    }
    return (X509TrustManager) trustManagers[0];
}
 
Example 30
public static SslContext createSSLClientContext(String sslFilePath,
		String sslPassword, String sslType, String algorithmName) {
	try {
		KeyStore ts = KeyStore.getInstance(sslType);
		TrustManagerFactory tf = TrustManagerFactory
				.getInstance(algorithmName);
		InputStream tsInputStream = new FileInputStream(
				getFileInputStream(sslFilePath));
		try {
			ts.load(tsInputStream, sslPassword.toCharArray());
			tf.init(ts);	
		} finally {
			tsInputStream.close();
		}
		
		//both-server
		KeyStore keyStore = KeyStore.getInstance(sslType);
		KeyManagerFactory kmf = KeyManagerFactory
				.getInstance(algorithmName);

		InputStream ksInputStream = new FileInputStream(
				getFileInputStream(sslFilePath));

		try {
			keyStore.load(ksInputStream, sslPassword.toCharArray());
			kmf.init(keyStore, sslPassword.toCharArray());

		} finally {
			ksInputStream.close();
		}
	
		return SslContextBuilder.forClient().trustManager(tf).keyManager(kmf).build();
	} catch (Exception ex) {
		ex.printStackTrace();
		return null;
	}
}