我一直在尝试绑定rest服务以进行支付。他们给了我p12格式的证书,并指示我使用OpenSSL库将其转换为pem格式。现在我有这两个文件。
key.pem(-----BEGIN ENCRYPTED PRIVATE KEY-----)
cert.pem(-----BEGIN CERTIFICATE-----)
我的目标是使用HttpsURLConnection调用这个rest服务。据我所知,我需要做以下事情:
KeyStore, SSLContext and then apply into httpsCon.setSSLSocketFactory(context.getSocketFactory());
我一直在寻找不同的解决方案,但找不到有效的解决方案。有人能提供工作实例吗?
这是为我工作的代码。希望它能帮助
public class Main {
@Autowired
ResourceLoader resourceLoader;
private static void applyCertificateInformation(HttpsURLConnection con, String password) throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {
KeyStore clientStore = KeyStore.getInstance("PKCS12");
clientStore.load(resourceLoader.getResource("my-cert.p12").getInputStream(), password.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(clientStore, password.toCharArray());
KeyManager[] kms = kmf.getKeyManagers();
TrustManager[] tms = new TrustManager[]{
new X509TrustManager() {
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(kms, tms, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
con.setSSLSocketFactory(sslContext.getSocketFactory());
}
}