java安全HTTPS工具类

 1 import java.io.FileInputStream;
 2 import java.security.KeyStore;
 3 import java.security.SecureRandom;
 4 
 5 import javax.net.ssl.HttpsURLConnection;
 6 import javax.net.ssl.KeyManagerFactory;
 7 import javax.net.ssl.SSLContext;
 8 import javax.net.ssl.SSLSocketFactory;
 9 import javax.net.ssl.TrustManagerFactory;
10 
11 import org.apache.commons.codec.digest.DigestUtils;
12 
13 
14 /**
15  * HTTPS组件
16  * @author bestmata
17  *
18  */
19 public class HTTPSCoder {
20 
21     private static final String TLS="TLS";
22     
23     private static final String SSL="SSL";
24     
25     
26     /**
27      * 获取keyStore
28      * 
29      * @param keyStorePath
30      * @param pwd
31      * @return
32      * @throws Exception
33      */
34     private static KeyStore getKeyStore(String keyStorePath,String pwd) throws Exception{
35         KeyStore ks=KeyStore.getInstance(KeyStore.getDefaultType());
36         FileInputStream in=new FileInputStream(keyStorePath);
37         ks.load(in, pwd.toCharArray());
38         in.close();
39         return ks;
40     }
41     
42     
43     /**
44      * 获取SSLSocektFactory
45      * 
46      * @param keyStorePath
47      * @param pwd
48      * @param trustStorePath
49      * @return
50      * @throws Exception
51      */
52     private static SSLSocketFactory getSSLSocketFactory(String keyStorePath,String pwd,String trustStorePath) throws Exception{
53         //实例话密匙库
54         KeyManagerFactory keyManageF=KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
55         KeyStore ks=getKeyStore(keyStorePath, pwd);
56         //初始化密匙工厂
57         keyManageF.init(ks, pwd.toCharArray());
58         //实例化信任库
59         TrustManagerFactory trustManageF=TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
60         //获得信任库
61         KeyStore trustStore=getKeyStore(trustStorePath, pwd);
62         trustManageF.init(trustStore);
63         //实例化SSL上下文
64         SSLContext ctx=SSLContext.getInstance(TLS);
65         ctx.init(keyManageF.getKeyManagers(), trustManageF.getTrustManagers(), new SecureRandom());
66         return ctx.getSocketFactory();
67     }
68     
69     
70     public static void configSSLSocketFactory(HttpsURLConnection conn,String keyStorePath,String pwd,String trustStorePath) throws Exception{
71         SSLSocketFactory sslSocketFactory=getSSLSocketFactory(keyStorePath, pwd, trustStorePath);
72         conn.setSSLSocketFactory(sslSocketFactory);
73         
74     }
75     
76     
77     public static void main(String[] args) {
78         System.out.println("e10adc3949ba59abbe56e057f20f883e");
79         System.out.println(DigestUtils.md5Hex("123456"));
80     }
81     
82 }
原文地址:https://www.cnblogs.com/huzi007/p/4330662.html