pondělí 21. listopadu 2011

Java - SSL for Jersey Client

Programové nastavení SSL na Jersey
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import java.security.KeyStore;
...

private void setupSSL(ClientConfig clientConfig) {
    try {        
        //Pokud se použije starší:
        //SSLContext.getInstance("SSL");
        //muže to skončit na chybe pri handshake
        SSLContext ctx = SSLContext.getInstance("TLS");

        KeyStore ks = KeyStore.getInstance("JKS");

        //Nacteni z filu
        //ks.load(new FileInputStream("d:/tmp7/clientstore"), "KeystorePassword".toCharArray());

        //nacteni z classpathy
        URL clientStore = getClass().getResource("/path/to/store/clientstore");
        ks.load(clientStore.openStream(), "KeystorePassword".toCharArray());

        //kdyz se pouzije
        //TrustManagerFactory.getInstance("SunX509", "SunJSSE");
        //Tak to nepojede na IBM jave, protože ta ma IbmX509 a ne SunX509
        //Naštěstí tohle funguje na obou. On uz si to dohleda:
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
        tmf.init(ks);
        TrustManager tms[] = tmf.getTrustManagers();
        ctx.init(null, tms, null);
        clientConfig.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(null, ctx));
    } catch (Exception ex) {
        throw new RuntimeException("Ssl setup failed", ex);
    }
}
...
ClientConfig clientConfig = new DefaultClientConfig();
client = Client.create(clientConfig);

Žádné komentáře:

Okomentovat