javax.net.ssl.TrustManagerFactory Java Examples

The following examples show how to use javax.net.ssl.TrustManagerFactory. 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 File: SSLContextBuilder.java    From carina with Apache License 2.0 8 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 File: AuthSSLProtocolSocketFactory.java    From iaf with Apache License 2.0 7 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 #3
Source File: MemorizingTrustManager.java    From cwac-netsecurity with 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 #4
Source File: PandroidModule.java    From pandroid with 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 #5
Source File: JAXRS20HttpsBookTest.java    From cxf with 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 #6
Source File: LdapConnectionConfig.java    From directory-ldap-api with 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 #7
Source File: SslTcpCommons.java    From linstor-server with 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 #8
Source File: JSSESocketFactory.java    From tomcatsrc with 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 #9
Source File: TlsHelper.java    From an2linuxclient with 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 #10
Source File: SecurityUtility.java    From pulsar with 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 #11
Source File: NettySslHandler.java    From jmqtt with 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 #12
Source File: SSLServerSocketHelper.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
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 #13
Source File: TestUtils.java    From grpc-java with 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 #14
Source File: DittoTrustManagerFactory.java    From ditto with 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 #15
Source File: MemorizingTrustManager.java    From Zom-Android-XMPP with GNU General Public License v3.0 6 votes vote down vote up
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 #16
Source File: SslContext.java    From netty-4.1.22 with 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 #17
Source File: SSLContextLoader.java    From Chronicle-Network with 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 #18
Source File: BouncrSSLSocketFactory.java    From bouncr with 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 #19
Source File: SSLStoreService.java    From elexis-3-core with 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 #20
Source File: TestInsecureQueryRunner.java    From presto with 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 #21
Source File: SecurityHelper.java    From MQTT-Essentials-A-Lightweight-IoT-Protocol with MIT License 6 votes vote down vote up
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 #22
Source File: XioTrustManagerFactory.java    From xio with Apache License 2.0 5 votes vote down vote up
private TrustManager[] buildTrustManagers(TrustManagerFactory factory) {
  ArrayList<TrustManager> result = new ArrayList<>();
  for (TrustManager tm : factory.getTrustManagers()) {
    if (tm instanceof X509TrustManager) {
      X509TrustManager delegate = (X509TrustManager) tm;
      result.add(new DelegatingTrustManager(delegate));
    } else {
      log.warn("TrustManager is not an instance of X509TrustManager, skipping. {}", tm);
    }
  }

  return result.toArray(new TrustManager[0]);
}
 
Example #23
Source File: EasyX509TrustManager.java    From olat with 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("SunX509");
    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 #24
Source File: AuthSSLConnectionSocket.java    From iaf with Apache License 2.0 5 votes vote down vote up
AuthSslTrustManager(KeyStore keystore, TrustManager[] trustmanagers) throws NoSuchAlgorithmException, KeyStoreException {
	if (trustmanagers == null || trustmanagers.length == 0) {
		TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
		factory.init(keystore);
		trustmanagers = factory.getTrustManagers();
	}
	if (trustmanagers.length != 1) {
		throw new NoSuchAlgorithmException("Only works with X509 trustmanagers");
	}
	trustManager = (X509TrustManager)trustmanagers[0];
}
 
Example #25
Source File: SsX509TrustManager.java    From android_volley_examples with Apache License 2.0 5 votes vote down vote up
private javax.net.ssl.X509TrustManager fetchTrustManager(InputStream keyStore, String keyStorePassword) throws GeneralSecurityException {
        javax.net.ssl.X509TrustManager ret = null;
        
        TrustManagerFactory tmf = prepareTrustManagerFactory(keyStore, keyStorePassword);
        TrustManager tms[] = tmf.getTrustManagers();            
        
        for (int i = 0; i < tms.length; i++) {
            if (tms[i] instanceof javax.net.ssl.X509TrustManager) {
                ret = (javax.net.ssl.X509TrustManager) tms[i];
//              break;
            }
        }
        
        return ret;
    }
 
Example #26
Source File: AuthSSLProtocolSocketFactoryForJsse10x.java    From iaf with Apache License 2.0 5 votes vote down vote up
AuthSslTrustManager(KeyStore keystore, TrustManager[] trustmanagers) throws NoSuchAlgorithmException, KeyStoreException {
	if (trustmanagers == null || trustmanagers.length == 0) {
		TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
		factory.init(keystore);
		trustmanagers = factory.getTrustManagers();
	}
	if (trustmanagers.length != 1) {
		throw new NoSuchAlgorithmException("Only works with X509 trustmanagers");
	}
	trustManager = (X509TrustManager)trustmanagers[0];
}
 
Example #27
Source File: InvokeSelfSignedServiceTest.java    From env-keystore with MIT License 5 votes vote down vote up
private void enableTrustStore(String trustedCert)
    throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, KeyManagementException {

  KeyStore ts = new EnvKeyStore(trustedCert, "password").keyStore();

  String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
  TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
  tmf.init(ts);

  SSLContext sc = SSLContext.getInstance("TLS");
  sc.init(null, tmf.getTrustManagers(), new SecureRandom());
  HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
 
Example #28
Source File: AbstractSecureJettyTest.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
private static SSLContext buildTrustSSLContext()
    throws IOException, GeneralSecurityException
{
    SSLContext sslCtx = SSLContext.getInstance( "TLS" );
    TrustManagerFactory caTrustManagerFactory = TrustManagerFactory.getInstance( getX509Algorithm() );
    caTrustManagerFactory.init( loadTrustStore() );
    sslCtx.init( null, caTrustManagerFactory.getTrustManagers(), null );
    return sslCtx;
}
 
Example #29
Source File: SSLConnectionTest.java    From talk-android with MIT License 5 votes vote down vote up
SSLContext createSSLContext() throws GeneralSecurityException, IOException {
    KeyStore ks = KeyStore.getInstance("JKS");
    File file = new File("src/test/resources/keystore.jks");
    ks.load(new FileInputStream(file), "password".toCharArray());

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

    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(ks);

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    return sslContext;
}
 
Example #30
Source File: SSLEngineFactory.java    From java-dcp-client with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new {@link SSLEngine} constructed from the config settings.
 *
 * @return a {@link SSLEngine} ready to be used.
 */
public SSLEngine get() {
  try {
    String pass = env.sslKeystorePassword();
    char[] password = pass == null || pass.isEmpty() ? null : pass.toCharArray();

    KeyStore ks = env.sslKeystore();
    if (ks == null) {
      ks = KeyStore.getInstance(KeyStore.getDefaultType());
      String ksFile = env.sslKeystoreFile();
      if (ksFile == null || ksFile.isEmpty()) {
        throw new IllegalArgumentException("Path to Keystore File must not be null or empty.");
      }
      ks.load(new FileInputStream(ksFile), password);
    }
    String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(defaultAlgorithm);
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(defaultAlgorithm);
    kmf.init(ks, password);
    tmf.init(ks);

    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    SSLEngine engine = ctx.createSSLEngine();
    engine.setUseClientMode(true);
    return engine;
  } catch (Exception ex) {
    throw new SSLException("Could not create SSLEngine.", ex);
  }
}