示例代码
点击查看代码
public static SSLContext getSslContext(){
try {
String keystorePath = Paths.get("stores","keystore.p12").toString();
String truststorePath = Paths.get("stores","truststore.jks").toString();
String keystorePassword = "12345678";
KeyStore clientKeystore = KeyStore.getInstance("PKCS12");
FileInputStream keystoreFis = new FileInputStream(keystorePath);
clientKeystore.load(keystoreFis, keystorePassword.toCharArray());
KeyStore trustKeystore = KeyStore.getInstance("jks");
FileInputStream trustKeystoreFis = new FileInputStream(truststorePath);
trustKeystore.load(trustKeystoreFis, keystorePassword.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance("sunx509");
kmf.init(clientKeystore, keystorePassword.toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance("sunx509");
tmf.init(trustKeystore);
SSLContext context = SSLContext.getInstance("SSL");
context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
return context;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
注意
- keystore:同时保存私钥和x509证书,可以是PKCS#12格式和jks格式
- truststore: 只保存x509证书,一般只使用jks格式,因为标准的PKCS#12格式被java认为不安全,需要增加bug声明后才可以用。这个bug声明只能用java的keytool来增加。