java使用指定的X509證書生成ssl上下文示例
阿新 • • 發佈:2022-05-26
示例程式碼
點選檢視程式碼
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來增加。