gpt4 book ai didi

java - 无法使用 SSL 在 java 客户端和 python 服务器之间执行通信

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

我正在尝试在 python 服务器和 java 客户端中使用使用 java keytool 生成的 key 和证书。我创建了 key 和 keystore 、导出证书、将证书添加到信任库、将 keystore 转换为标准 pkcs 格式,然后从 pkcs 中提取 key 和证书以在 python 服务器中使用。 (前三步来自 here,后三步来自 here)以下是详细步骤:

  1. 创建 keystore 、私钥和证书

    keytool -genkey -alias ssl_key -keyalg RSA -keypass passwd123 -keystore keystore.jks -storepass passwd123
  2. 将证书从 keystore 导出到 .cer 文件

    keytool -export -alias ssl_key -file ssl_key.cer -keystore keystore.jks -storepass passwd123
  3. 将证书从 keystore 导出到信任库

    keytool -import -v -trustcacerts -alias ssl_key -keypass passwd123 -file ssl_key.cer -keystore truststore.jks -storepass passwd123
  4. 将 keystore 从 keytool 的专有格式导出为标准格式

    keytool -importkeystore -srckeystore keystore.jks -destkeystore stdkeystore.p12 -deststoretype PKCS12 -srcalias ssl_key -deststorepass passwd123 -destkeypass passwd123
  5. 使用 openssl 从标准格式 keystore 导出证书

    openssl pkcs12 -in stdkeystore.p12 -nokeys -out cert.pem
  6. 使用 openssl 从标准格式 keystore 导出未加密的私钥,如下所示:

    openssl pkcs12 -in stdkeystore.p12  -nodes -nocerts -out key.pem

我的小型python服务器和java客户端如下:

server.py

import socket
import ssl

def start_server_ssl():

socketObj = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('127.0.0.1', 6000)
socketObj.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
socketObj.bind(server_address)
socketObj.listen(10)

while True:
try:
print("Awaiting connection...")
data_socket, client_address = socketObj.accept()
ssl_socket = ssl.wrap_socket(socketObj,
server_side = True,
certfile="cert.pem",
keyfile="key.pem")

reading_status = True
data = bytearray()
data_decoded = ""
while(reading_status):
message_chunks = data_socket.recv(90000)
data.extend(message_chunks)

print(data)
data_decoded = str(data.decode("utf-8"))
#data_decoded = str(data.decode())

if(data_decoded.startswith("<<startMessage>>")):
if(data_decoded.endswith("<<endMessage>>")):
reading_status = False
print(data_decoded);

except socket.error as msg:
print (msg)

ssl_socket.shutdown(socket.SHUT_RDWR)
ssl_socket.close()

if __name__ == '__main__':
start_server_ssl()

Client4Py.java

import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;

public class Client4Py {
static KeyStore ks;
static KeyManagerFactory kmf;
static TrustManagerFactory tmf;
static SSLContext sc;
static TrustManager[] trustManagers;

static {
try {
ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream("D:\\javasslstores\\truststore.jks"), "passwd123".toCharArray());

kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, "passwd123".toCharArray());

tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(ks);

sc = SSLContext.getInstance("TLS");

sc.init(null, tmf.getTrustManagers(), null);
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println(e.getStackTrace());
}
}

public static void main(String[] args) throws IOException {
SSLSocketFactory ssf = sc.getSocketFactory();
SSLSocket socket = (SSLSocket) ssf.createSocket("127.0.0.1", 6000);
socket.startHandshake();

PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),StandardCharsets.UTF_8)));
//PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));

out.println("<<startMessage>>");
out.println("Message from Client4Py");
out.println("<<endMessage>>");
out.flush();

if (out.checkError())
System.out.println(
"SSLSocketClient: java.io.PrintWriter error");

out.close();
socket.close();
}
}

首次运行服务器和客户端后,服务器控制台的输出如下:

Awaiting connection...
bytearray(b'\x16\x03\x03\x00\xc1\x01\x00\x00\xbd\x03\x03["}o\x12\x01\xb2\xd4E\xa1\x1fy\xa8/d\x11\xd2\x00)\\t\x9a:\xb6\n\xcd\x03\x05\xbe\xe58\xd6\x00\x00:\xc0#\xc0\'\x00<\xc0%\xc0)\x00g\x00@\xc0\t\xc0\x13\x00/\xc0\x04\xc0\x0e\x003\x002\xc0+\xc0/\x00\x9c\xc0-\xc01\x00\x9e\x00\xa2\xc0\x08\xc0\x12\x00\n\xc0\x03\xc0\r\x00\x16\x00\x13\x00\xff\x01\x00\x00Z\x00\n\x004\x002\x00\x17\x00\x01\x00\x03\x00\x13\x00\x15\x00\x06\x00\x07\x00\t\x00\n\x00\x18\x00\x0b\x00\x0c\x00\x19\x00\r\x00\x0e\x00\x0f\x00\x10\x00\x11\x00\x02\x00\x12\x00\x04\x00\x05\x00\x14\x00\x08\x00\x16\x00\x0b\x00\x02\x01\x00\x00\r\x00\x18\x00\x16\x06\x03\x06\x01\x05\x03\x05\x01\x04\x03\x04\x01\x03\x03\x03\x01\x02\x03\x02\x01\x02\x02')
Traceback (most recent call last):
File "D:\Mahesh\workspaces\workspace6\PythonServer\server.py", line 44, in <module>
start_server_ssl()
File "D:\Mahesh\workspaces\workspace6\PythonServer\server.py", line 29, in start_server_ssl
data_decoded = str(data.decode("utf-8"))
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc1 in position 4: invalid start byte

我取消注释客户端和服务器代码中的 utf-8 编码解码行,最终在服务器控制台上得到以下输出:

Awaiting connection...
bytearray(b'\x16\x03\x03\x00\xc1\x01\x00\x00\xbd\x03\x03["\x7f>s\x04\x15S\x14\xb0\xa2\xa0\x7f\x90}@\xe8\xa3:\x15\x04z\xeb\x986\\b\xe9\xe0v=\x1f\x00\x00:\xc0#\xc0\'\x00<\xc0%\xc0)\x00g\x00@\xc0\t\xc0\x13\x00/\xc0\x04\xc0\x0e\x003\x002\xc0+\xc0/\x00\x9c\xc0-\xc01\x00\x9e\x00\xa2\xc0\x08\xc0\x12\x00\n\xc0\x03\xc0\r\x00\x16\x00\x13\x00\xff\x01\x00\x00Z\x00\n\x004\x002\x00\x17\x00\x01\x00\x03\x00\x13\x00\x15\x00\x06\x00\x07\x00\t\x00\n\x00\x18\x00\x0b\x00\x0c\x00\x19\x00\r\x00\x0e\x00\x0f\x00\x10\x00\x11\x00\x02\x00\x12\x00\x04\x00\x05\x00\x14\x00\x08\x00\x16\x00\x0b\x00\x02\x01\x00\x00\r\x00\x18\x00\x16\x06\x03\x06\x01\x05\x03\x05\x01\x04\x03\x04\x01\x03\x03\x03\x01\x02\x03\x02\x01\x02\x02')
Traceback (most recent call last):
File "D:\Mahesh\workspaces\workspace6\PythonServer\server.py", line 44, in <module>
start_server_ssl()
File "D:\Mahesh\workspaces\workspace6\PythonServer\server.py", line 30, in start_server_ssl
data_decoded = str(data.decode())
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc1 in position 4: invalid start byte

我觉得我错过了什么。 SSL 或编码的一些基础知识。我可以使用 python SSLSocket 直接使用上面解释的从 java keystore 生成的 pem 文件吗?还是我必须确保更像用于生成 key 和证书的密码?

欢迎任何消除我无知的链接/资源......

最佳答案

我用这个例子替换了你的server.py。您的服务器关于 key 和证书没有任何问题。

server.py

import socket
from socket import AF_INET, SOCK_STREAM, SO_REUSEADDR, SOL_SOCKET, SHUT_RDWR
import ssl

KEYFILE = 'key.pem'
CERTFILE = 'cert.pem'

def print_data(s):
while True:
data = s.recv(8192)
print(data.decode("utf-8"))
if data == b'':
break
s.send(b'This is a response.')
print('Connection closed')
s.close()

def start_server_ssl(address):
s = socket.socket(AF_INET, SOCK_STREAM)
s.bind(address)
s.listen(1)
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)

ssl_socket = ssl.wrap_socket(s, keyfile=KEYFILE, certfile=CERTFILE, server_side=True)
print("Awaiting connection...")

while True:
try:
(c,a) = ssl_socket.accept()
print('Got connection', c, a)
print_data(c)
except socket.error as e:
print('Error: {0}'.format(e))

start_server_ssl((socket.gethostbyname('localhost'), 6000))

关于java - 无法使用 SSL 在 java 客户端和 python 服务器之间执行通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50860354/

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