如何使用 PEM 文件在 Java 中创建 SSL 套接字?

2022-01-25 00:00:00 ssl certificate java pem jks

查看相关问题.

我有一个 PEM 文件提供给我,并被告知在建立连接到 c++ 服务器以进行某些 API 调用的 SSL 套接字时需要它.有谁知道我如何读取 PEM 文件并进行连接?我还得到了释义密码.

I have a PEM file provided to me and was told that it will be needed in establishing a SSL socket that connects to a c++ server for some API calls. Does anyone know how I can read in the PEM file and connect? I was also given the parapharse password.

推荐答案

听起来 PEM 文件是您用来登录服务器的客户端证书.如果它是客户端证书,并且听起来确实如此,那么您可能还需要一个 ca 证书文件来验证服务器证书以建立连接.

It sounds like the PEM file is a client cert for you to use to login to the server. If it is the client cert, and it sounds like it is, you will likely need a ca cert file also to use in validating the servers certificate in order to establish a connection.

CA 证书需要进入信任库,您的客户端证书需要进入密钥库.在 Java 中,这两个都是 JKS(尽管它对 PKCS12 的支持有限.)JRE 以及每个用户都有默认的密钥库/信任库位置.您还可以在代码中为这些文件指定外部位置,如下例所示.commons-ssl库貌似可以直接支持PEM,不需要JKS,不过我没用过.

The CA certs need to go into a truststore and your client certs need to go into a keystore. In Java, both of these will be JKS (although it has limited support for PKCS12.) There are default keystore/truststore locations for the JRE as well as for each user. You can also specify external locations for these files in your code, as in the examples below. The commons-ssl library seems to be able to support PEM directly, without the need for JKS, but I haven't used it.

Java 中这些密钥库的默认密码是changeit",不带引号.

The default passphrase for these keystores in Java is "changeit" without the quotes.

此页面显示您必须将 PEM 读入您的密钥库/信任库.这是 另一个例子.

This page shows you have to read the PEM into your keystore/truststore. Here is another example.

正确设置信任库和密钥库后,您需要通过以下 JSSE 系统属性 到你的 JVM:

Once you have your truststore and keystore set up properly, you need to pass the following JSSE system properties to your JVM:

javax.net.ssl.keyStore
javax.net.ssl.keyStoreType
javax.net.ssl.keyStorePassword
javax.net.ssl.trustStore
javax.net.ssl.trustStoreType
javax.net.ssl.trustStorePassword

您可以将它们指定为 JRE 的 -D 参数,或者如下例所示,以编程方式.

You may specify them as -D parameters to the JRE or, as in the examples below, programatically.

完成后,这里是创建套接字的 commons-ssl 示例.此外,这是 SSLSocket.这里还有一个不使用任何 apache commons 的 示例.

Once you finish that, heres a commons-ssl example of creating a socket. Also, heres the Java api for SSLSocket. Heres also an example that doesn't use any apache commons.

相关文章