Xử lý khi làm việc với SSL trong Java

Khi bạn làm việc với 1 server chạy SSL tương tác bằng Java thì nếu không được server tin tưởng bạn sẽ không thể làm việc tiếp được, dưới đây là một ví dụ về 1 class có tên SSLHandler.java có thể tham khảo để xử lý một số ngoại lệ khi làm việc với SSL trong Java.

Để làm được trước hết ta cần 1 file keystore hoặc #PKCS12, ví dụ với 1 Web server chạy SSL thì chỉ cần truy cập website tải chứng thư SSL của website về dưới dạng file .cer hoặc .crt sau đó dùng keytool của Java để đóng JKS, mình thường làm vậy.
Ở đây mình code Maven project nên sẽ đặt file example.jks trong thư mục src/main/resources, đường dẫn sẽ như sau src/main/resources/example.jks.

Tại đây mình cũng tạo một file truststoreconfig.properties và đường dẫn của nó như sau src/main/resources/truststoreconfig.properties.

File truststoreconfig.properties có nội dung dạng như sau:

ssl.trustStore=example.jks
ssl.trustStorePassword=123456
ssl.trustStoreType=JKS

File SSLHandler.java có nội dung dạng như sau:

package applications.util;

import java.io.File;
import java.io.InputStream;
import java.util.Properties;

/**
 * 
 * SSLHandler
 */
public class SSLHandler {

    private static final String trustStore;
    private static final String trustStorePassword;
    private static final String trustStoreType;
    
    // load properties file
    static {
        Properties props = new Properties();
        InputStream is = null;
        
        try {
            is = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("truststoreconfig.properties");
            if (is == null) {
                throw new RuntimeException("Cannot read truststoreconfig.properties file!");
            }
            
            props.load(is);
            trustStore = props.getProperty("ssl.trustStore");
            trustStorePassword = props.getProperty("ssl.trustStorePassword");
            trustStoreType = props.getProperty("ssl.trustStoreType");
        } catch (Exception e) {
            throw new RuntimeException("Cannot read truststoreconfig.properties file! detail:\r\n" + e);
        }
    }
    
    private static String _getTrustStorePath() {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        File file = new File(classLoader.getResource("truststoreconfig.properties").getFile());
        
        return file.getParentFile().getAbsolutePath();
    }
    
    /**
     * 
     * setSSL
     */
    public static void setSSL() {
        System.setProperty("javax.net.ssl.trustStore", _getTrustStorePath());
        System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword);
        System.setProperty("javax.net.ssl.trustStoreType", trustStoreType);
    }
    
}

Để sử dụng trước khi trao đổi với server chạy SSL chỉ cần gọi hàm setSSL trước xử lý của bạn:

SSLHandler.setSSL();
...

Leave a Reply

Your email address will not be published. Required fields are marked *