如何在javassl中加载本地客户端证书?

m528fe3b  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(446)

我尝试使用tls连接到服务器的套接字,该套接字需要使用client.java代码进行客户端身份验证

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

public class Client {
    public static void main(String[] args){
        System.setProperty("javax.net.ssl.trustStore", "/home/toni/.keystore");
        System.setProperty("javax.net.ssl.trustStorePassword", "jOk<>123");

        String host = "localhost";
        Integer port = 8000;
        byte[] data = new byte[4096];

        SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
        try(
            SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
            InputStream in = socket.getInputStream();
            OutputStream out = socket.getOutputStream();
        ){
            out.write("Hi, I am client".getBytes());
            in.read(data);
            System.out.println(new String(data));
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

但是client.java似乎没有将本地客户端证书发送到服务器,所以服务器返回一个错误:

ssl.SSLError: [SSL: PEER_DID_NOT_RETURN_A_CERTIFICATE] peer did not return a certificate (_ssl.c:852)

这是我的 keytool -list ```
Keystore type: PKCS12
Keystore provider: SUN

Your keystore contains 2 entries

client, Aug 20, 2020, PrivateKeyEntry,
Certificate fingerprint (SHA-256): 41:36:F0:A5:38:DA:99:D1:6A:B1:44:87:9C:00:CF:73:FC:96:48:22:79:B5:3A:9A:ED:44:C8:AA:CA:97:45:5E
localhost, Aug 20, 2020, trustedCertEntry,
Certificate fingerprint (SHA-256): 1A:CB:DA:E3:ED:BF:E0:C8:C1:13:13:8C:A4:FB:20:48:53:54:80:D3:36:14:35:9C:EF:AF:5B:16:E2:54:97:B8

如何加载my client.java `client` 上面的别名证书,并在与服务器握手时使用它?
qyzbxkaa

qyzbxkaa1#

我刚刚了解了keystore和truststore之间的区别。实际上,在java中,我不需要在客户端显式地指定客户端证书。我只需要像这样声明我的密钥库:

String file = "/home/toni/.keystore";
        String password = "jOk<>123";
        System.setProperty("javax.net.ssl.trustStore", file);
        System.setProperty("javax.net.ssl.trustStorePassword", password);
        System.setProperty("javax.net.ssl.keyStore", file);
        System.setProperty("javax.net.ssl.keyStorePassword", password);

相关问题