且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用给定的 p12 证书连接到 https 站点

更新时间:2023-02-24 12:15:41

如果您想尝试对 SSL 配置进行编码,您可以使用提供给您的 P12 文件,而无需将其转换为 JKS.此外,您将需要使用 P12 中的私钥,而不仅仅是您复制到 JKS 中的证书.不确定这是否会直接满足您的需求,但这可能会让您走上正确的道路:

If you want to attempt to code up the SSL configuration, you could use the P12 file given to you without having to convert it into a JKS. Also, you will need to use the private key in the P12, and not just the certificates that you copied into the JKS. Not sure if this will suit your needs directly, but this may put you on the right path:

        KeyStore clientStore = KeyStore.getInstance("PKCS12");
        clientStore.load(new FileInputStream("test.p12"), "testPass".toCharArray());

        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(clientStore, "testPass".toCharArray());
        KeyManager[] kms = kmf.getKeyManagers();

        KeyStore trustStore = KeyStore.getInstance("JKS");
        trustStore.load(new FileInputStream("cacerts"), "changeit".toCharArray());

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);
        TrustManager[] tms = tmf.getTrustManagers();

        SSLContext sslContext = null;
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(kms, tms, new SecureRandom());

        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        URL url = new URL("https://www.testurl.com");

        HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();

以这种方式配置 trustStore 是可选的.您可以使用 P12 链中的所有证书创建 JKS,或者只需确保它们在您的 JRE 的 cacerts 文件中.至于keytool,作为参考,您可以在P12上运行keytool命令(指定-storetype pkcs12),但不能将P12导入JKS.您也不能使用 keytool 命令仅从 P12 导出密钥.

Configuring the trustStore this way is optional. You could create a JKS with all of the certificates in the chain of your P12, or just make sure they are in your JRE's cacerts file. As for keytool, for reference, you can run keytool commands on a P12 (specify -storetype pkcs12), but cannot import a P12 into a JKS. You also cannot export just a key from a P12 with the keytool command.

我目前没有设置服务器来测试此代码,所以试一试,看看您是否仍然收到 403 错误.

I have no servers setup at the moment to test out this code, so give it a shot and see if you still receive the 403 error.