create java keystore to avoid exceptions of JSSE

All the time I got exceptions when I met ssl or https in java.
To ignore those exceptions you need to prepare keystore and init TrustManager.

Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty

  • Prepare an empty keystore for JSSE.
  • By default, a cert file in jre; %JRE_HOE%\lib\security\cacerts exists. You can use it or create our own keystore. *
    1
    2
    %JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg RSA
    copy %USER_HOME%\.keystore d:\trustKeyStore.jks

-Djavax.net.ssl.trustStore=path/to/trustKeyStore.jks
or
System.setProperty(“javax.net.ssl.trustStore”, “trustKeyStore.jks”);
//System.setProperty(“javax.net.ssl.trustStorePassword”,password);

  • Just invoke initTrustManager in the begging of your system.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    static class MyTrustManager implements javax.net.ssl.X509TrustManager, javax.net.ssl.TrustManager {
    @Override
    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
    return null;
    }

    public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
    return true;
    }

    public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
    return true;
    }

    @Override
    public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException {
    return;
    }

    @Override
    public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException {
    return;
    }
    }

    static private TrustManager[] getTrustManager() {
    javax.net.ssl.TrustManager[] trustAllCerts = { new MyTrustManager() };
    return trustAllCerts;
    }

    static public void initTrustManager() throws NoSuchAlgorithmException, KeyManagementException{
    Protocol.registerProtocol("https", new Protocol("https", new MySSLSocketFactory(), 443));

    // Install the all-trusting trust manager
    final SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, getTrustManager(), new java.security.SecureRandom());
    // Create an ssl socket factory with our all-trusting manager
    final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
    }

reference: http://docs.oracle.com/javase/7/docs/technotes/guides/security/jsse/JSSERefGuide.html#X509TrustManager
reference: http://tomcat.apache.org/tomcat-5.5-doc/ssl-howto.html