Search in sources :

Example 31 with TrustManagerFactory

use of javax.net.ssl.TrustManagerFactory in project okhttp-OkGo by jeasonlzy.

the class HttpsUtils method prepareTrustManager.

private static TrustManager[] prepareTrustManager(InputStream... certificates) {
    if (certificates == null || certificates.length <= 0)
        return null;
    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        // 创建一个默认类型的KeyStore,存储我们信任的证书
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null);
        int index = 0;
        for (InputStream certStream : certificates) {
            String certificateAlias = Integer.toString(index++);
            // 证书工厂根据证书文件的流生成证书 cert
            Certificate cert = certificateFactory.generateCertificate(certStream);
            // 将 cert 作为可信证书放入到keyStore中
            keyStore.setCertificateEntry(certificateAlias, cert);
            try {
                if (certStream != null)
                    certStream.close();
            } catch (IOException e) {
                OkLogger.e(e);
            }
        }
        //我们创建一个默认类型的TrustManagerFactory
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        //用我们之前的keyStore实例初始化TrustManagerFactory,这样tmf就会信任keyStore中的证书
        tmf.init(keyStore);
        //通过tmf获取TrustManager数组,TrustManager也会信任keyStore中的证书
        return tmf.getTrustManagers();
    } catch (Exception e) {
        OkLogger.e(e);
    }
    return null;
}
Also used : InputStream(java.io.InputStream) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) IOException(java.io.IOException) CertificateFactory(java.security.cert.CertificateFactory) KeyStore(java.security.KeyStore) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 32 with TrustManagerFactory

use of javax.net.ssl.TrustManagerFactory in project AndroidAsync by koush.

the class SSLTests method testKeys.

public void testKeys() throws Exception {
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(getContext().getResources().openRawResource(R.raw.keystore), "storepass".toCharArray());
    kmf.init(ks, "storepass".toCharArray());
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    KeyStore ts = KeyStore.getInstance(KeyStore.getDefaultType());
    ts.load(getContext().getResources().openRawResource(R.raw.keystore), "storepass".toCharArray());
    tmf.init(ts);
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    AsyncHttpServer httpServer = new AsyncHttpServer();
    httpServer.listenSecure(8888, sslContext);
    httpServer.get("/", new HttpServerRequestCallback() {

        @Override
        public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
            response.send("hello");
        }
    });
    Thread.sleep(1000);
    AsyncHttpClient.getDefaultInstance().getSSLSocketMiddleware().setSSLContext(sslContext);
    AsyncHttpClient.getDefaultInstance().getSSLSocketMiddleware().setTrustManagers(tmf.getTrustManagers());
    AsyncHttpClient.getDefaultInstance().executeString(new AsyncHttpGet("https://localhost:8888/"), null).get();
}
Also used : AsyncHttpGet(com.koushikdutta.async.http.AsyncHttpGet) HttpServerRequestCallback(com.koushikdutta.async.http.server.HttpServerRequestCallback) AsyncHttpServerRequest(com.koushikdutta.async.http.server.AsyncHttpServerRequest) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) AsyncHttpServer(com.koushikdutta.async.http.server.AsyncHttpServer) AsyncHttpServerResponse(com.koushikdutta.async.http.server.AsyncHttpServerResponse) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) KeyManagerFactory(javax.net.ssl.KeyManagerFactory)

Example 33 with TrustManagerFactory

use of javax.net.ssl.TrustManagerFactory in project quickstarts by jboss-switchyard.

the class CamelNettyBindingTest method sendTextMessageThroughTcp.

@Test
public void sendTextMessageThroughTcp() throws Exception {
    // replace existing implementation for testing purposes
    _testKit.removeService("SecuredGreetingService");
    final MockHandler greetingService = _testKit.registerInOnlyService("SecuredGreetingService");
    greetingService.forwardInToOut();
    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(new FileInputStream("users.jks"), "changeit".toCharArray());
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(keystore);
    SSLContext context = SSLContext.getInstance("TLS");
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keystore, "changeit".toCharArray());
    context.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);
    SSLSocketFactory sf = context.getSocketFactory();
    Socket clientSocket = sf.createSocket("localhost", 3939);
    DataOutputStream outputStream = new DataOutputStream(clientSocket.getOutputStream());
    // lets write payload directly as bytes to avoid encoding mismatches
    outputStream.write(PAYLOAD.getBytes());
    outputStream.flush();
    // sleep a bit to receive message on camel side
    Thread.sleep(50);
    clientSocket.close();
    greetingService.waitForOKMessage();
    final LinkedBlockingQueue<Exchange> recievedMessages = greetingService.getMessages();
    assertThat(recievedMessages, is(notNullValue()));
    final Exchange recievedExchange = recievedMessages.iterator().next();
    assertThat(PAYLOAD, is(equalTo(recievedExchange.getMessage().getContent(String.class))));
}
Also used : Exchange(org.switchyard.Exchange) DataOutputStream(java.io.DataOutputStream) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) MockHandler(org.switchyard.test.MockHandler) SSLContext(javax.net.ssl.SSLContext) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) Socket(java.net.Socket) MulticastSocket(java.net.MulticastSocket) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) Test(org.junit.Test)

Example 34 with TrustManagerFactory

use of javax.net.ssl.TrustManagerFactory in project apjp by jvansteirteghem.

the class HTTPS method createSSLServerSocket.

public static synchronized SSLServerSocket createSSLServerSocket() throws HTTPSException {
    try {
        KeyStore defaultKeyStore = getDefaultKeyStore();
        SSLContext sslContext = SSLContext.getInstance("TLS");
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(defaultKeyStore, "APJP".toCharArray());
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(defaultKeyStore);
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
        SSLServerSocketFactory sslServerSocketFactory = (SSLServerSocketFactory) sslContext.getServerSocketFactory();
        return (SSLServerSocket) sslServerSocketFactory.createServerSocket();
    } catch (Exception e) {
        logger.log(2, "HTTPS/CREATE_SSL_SERVER_SOCKET: EXCEPTION", e);
        throw new HTTPSException("HTTPS/CREATE_SSL_SERVER_SOCKET", e);
    }
}
Also used : TrustManagerFactory(javax.net.ssl.TrustManagerFactory) SSLServerSocketFactory(javax.net.ssl.SSLServerSocketFactory) SSLContext(javax.net.ssl.SSLContext) SSLServerSocket(javax.net.ssl.SSLServerSocket) KeyStore(java.security.KeyStore) KeyManagerFactory(javax.net.ssl.KeyManagerFactory)

Example 35 with TrustManagerFactory

use of javax.net.ssl.TrustManagerFactory in project ribbon by Netflix.

the class MockHttpServer method before.

public void before(final Description description) throws Exception {
    this.service = Executors.newFixedThreadPool(threadCount, new ThreadFactoryBuilder().setDaemon(true).setNameFormat("TestHttpServer-%d").build());
    InetSocketAddress inetSocketAddress = new InetSocketAddress("localhost", 0);
    if (hasSsl) {
        byte[] sampleTruststore1 = Base64.decode(TEST_TS1);
        byte[] sampleKeystore1 = Base64.decode(TEST_KS1);
        keystore = File.createTempFile("SecureAcceptAllGetTest", ".keystore");
        truststore = File.createTempFile("SecureAcceptAllGetTest", ".truststore");
        FileOutputStream keystoreFileOut = new FileOutputStream(keystore);
        try {
            keystoreFileOut.write(sampleKeystore1);
        } finally {
            keystoreFileOut.close();
        }
        FileOutputStream truststoreFileOut = new FileOutputStream(truststore);
        try {
            truststoreFileOut.write(sampleTruststore1);
        } finally {
            truststoreFileOut.close();
        }
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(new FileInputStream(keystore), PASSWORD.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, PASSWORD.toCharArray());
        KeyStore ts = KeyStore.getInstance("JKS");
        ts.load(new FileInputStream(truststore), PASSWORD.toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ts);
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        HttpsServer secureServer = HttpsServer.create(inetSocketAddress, 0);
        secureServer.setHttpsConfigurator(new HttpsConfigurator(sc) {

            public void configure(HttpsParameters params) {
                SSLContext c = getSSLContext();
                SSLParameters sslparams = c.getDefaultSSLParameters();
                params.setSSLParameters(sslparams);
            }
        });
        server = secureServer;
    } else {
        server = HttpServer.create(inetSocketAddress, 0);
    }
    server.setExecutor(service);
    for (Entry<String, HttpHandler> handler : handlers.entrySet()) {
        server.createContext(handler.getKey(), handler.getValue());
    }
    server.start();
    localHttpServerPort = server.getAddress().getPort();
    System.out.println(description.getClassName() + " TestServer is started: " + getServerUrl());
}
Also used : HttpHandler(com.sun.net.httpserver.HttpHandler) HttpsConfigurator(com.sun.net.httpserver.HttpsConfigurator) InetSocketAddress(java.net.InetSocketAddress) HttpsParameters(com.sun.net.httpserver.HttpsParameters) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) SSLParameters(javax.net.ssl.SSLParameters) FileOutputStream(java.io.FileOutputStream) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) HttpsServer(com.sun.net.httpserver.HttpsServer)

Aggregations

TrustManagerFactory (javax.net.ssl.TrustManagerFactory)233 KeyStore (java.security.KeyStore)145 SSLContext (javax.net.ssl.SSLContext)111 TrustManager (javax.net.ssl.TrustManager)89 KeyManagerFactory (javax.net.ssl.KeyManagerFactory)82 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)55 X509TrustManager (javax.net.ssl.X509TrustManager)55 FileInputStream (java.io.FileInputStream)53 IOException (java.io.IOException)48 KeyStoreException (java.security.KeyStoreException)47 InputStream (java.io.InputStream)45 CertificateException (java.security.cert.CertificateException)35 KeyManagementException (java.security.KeyManagementException)30 X509Certificate (java.security.cert.X509Certificate)25 SecureRandom (java.security.SecureRandom)22 KeyManager (javax.net.ssl.KeyManager)17 UnrecoverableKeyException (java.security.UnrecoverableKeyException)16 CertificateFactory (java.security.cert.CertificateFactory)15 GeneralSecurityException (java.security.GeneralSecurityException)13 File (java.io.File)11