標籤:
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 bestmata17 *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 * 擷取keyStore28 * 29 * @param keyStorePath30 * @param pwd31 * @return32 * @throws Exception33 */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 * 擷取SSLSocektFactory45 * 46 * @param keyStorePath47 * @param pwd48 * @param trustStorePath49 * @return50 * @throws Exception51 */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 }
java安全HTTPS工具類