Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use SSL in Square MockWebServer?

I try to enable SSL on Square's MockWebServer to mock all webservice calls in my Android App under Test. I want to enable SSL to get the same errors like under real conditions. I don't want to disable SSL for the tests or implement a SSL-ignoring HTTPClient.

On every request I get this javax.net.ssl.SSLPeerUnverifiedExceptionecxeption:

org.springframework.web.client.ResourceAccessException: I/O error on POST request for "https://localhost:42451/api/blabla": No peer certificate; nested exception is javax.net.ssl.SSLPeerUnverifiedException: No peer certificate

It seems I need to set a certificate for the MockWebServer. But I don't know how...

This is how I tried to enable SSL:

SSLContext sslContext = new SslContextBuilder(InetAddress.getLocalHost().getHostName()).build();
server.useHttps(sslContext.getSocketFactory(), true);

Or:

SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, null, null);
server.useHttps(sslContext.getSocketFactory(), false);

Can anyone help?

like image 414
StefanTo Avatar asked Dec 02 '15 07:12

StefanTo


1 Answers

You will need to create your own keystore:

keytool -genkey -v -keystore mystore.keystore.jks -alias alias_name -keyalg RSA -keysize 2048 -validity 10000

or see : https://developer.android.com/studio/publish/app-signing.html

After creating the keystore, load it in your code and use it in the following way:

        FileInputStream stream = new FileInputStream("mystore.keystore.jks");
        char[] serverKeyStorePassword = "yourcode".toCharArray();
        KeyStore serverKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        serverKeyStore.load(stream, 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(), null);
        SSLSocketFactory sf = sslContext.getSocketFactory();
        mockWebServer.useHttps(sf, false);
like image 80
leon karabchesvky Avatar answered Nov 07 '22 22:11

leon karabchesvky