gpt4 book ai didi

java - 带有 openssl/java 的双向 SSL

转载 作者:太空宇宙 更新时间:2023-11-03 14:47:39 26 4
gpt4 key购买 nike

我有一个 java 客户端应用程序,它希望以双向 SSL 连接到服务器。我创建了一对公钥/私钥。公钥名称为 key.cert,私钥名称为 key.pem。然后服务器端给我一个带有 server.cert 名称的公钥。我的问题是:

  1. 什么将我端(客户端)中的三个 key (key.cert\key.pem\server.cert)转换为 java Key Store(JKS)
  2. 什么在代码中创建一个 Socket 以连接到服务器?

最佳答案

        System.out.println("Connecting to " +IP + "port "
+ Port);

// load client private key
KeyStore clientKeys = KeyStore.getInstance("JKS");
clientKeys.load(
new FileInputStream(ProjectConfig
.getProperty("KeyStoreAndTrustStore")),
ProjectConfig.getProperty(
"KeyStoreAndTrustStorePassword")
.toCharArray());
KeyManagerFactory clientKeyManager = KeyManagerFactory
.getInstance("SunX509");
clientKeyManager.init(
clientKeys,
ProjectConfig.getProperty(
"KeyStoreAndTrustStorePassword")
.toCharArray());
// load server public key
KeyStore serverPub = KeyStore.getInstance("JKS");
serverPub.load(
new FileInputStream(ProjectConfig
.getProperty("KeyStoreAndTrustStore")),
ProjectConfig.getProperty(
"KeyStoreAndTrustStorePassword")
.toCharArray());
TrustManagerFactory trustManager = TrustManagerFactory
.getInstance("SunX509");
trustManager.init(serverPub);

// use keys to create SSLSoket
SSLContext ssl = SSLContext.getInstance("TLS");
ssl.init(clientKeyManager.getKeyManagers(),
trustManager.getTrustManagers(),
SecureRandom.getInstance("SHA1PRNG"));

sslClient = (SSLSocket) ssl.getSocketFactory().createSocket(
IP, Port);

sslClient.setSoTimeout(TimeOut);
System.out.println("connected to "
+ sslClient.getRemoteSocketAddress());
OutputStream outToServer = sslClient.getOutputStream();

out = new DataOutputStream(outToServer);
String contentToSend = ((String)Paylod);

out.writeUTF(contentToSend);
System.out.println(" sending data.... " + contentToSend);
InputStream inFromServer = sslClient.getInputStream();
in = new DataInputStream(inFromServer);
response = in.readUTF();
System.out.println("Server says.... " + response);
sslClient.close();

关于java - 带有 openssl/java 的双向 SSL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37539943/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com