SSL 消息编码

SSL messages encoding

我正在尝试在 Python 3.4 下构建 SSL 服务器。重点是通过基于JSON数据格式的定义协议与程序进行通信和交换数据。

所以我在 SSL 协议中使用了基本的 "echo server" 和客户端并修改了它们以查看是否可以交换数据。它起作用了,发送 "hello" 的一侧是 b"hello" 的另一侧,它是双向的。

我启动服务器端,连接程序,通信成功,但是: 我期待这样的事情:LOGIN:n::{“user”:”XXXXX”, , ”password”:”YYYYY ”, app”:”ZZZZZ”, “app_ver”:”zzz”, ”protocol”:”xxx”,”protocol_ver”:”xxxx”} 来自客户端(程序)

但是我得到的是这样的东西b"\x16\x03\x03\x00\x8e\x01\x00\x00\x8a\x03\x03^\x9e\xeb\xd8\x8f\xd9 \x05v\xbbF:}\xda\x17\xf7\x13\xff\xa9\xde=5\xfb_\xbco\x16\x96EL#\x00\x00*\xc0,\xc0+\xc00\xc0/\x00\x9f\x00\x9e\xc0$\xc0#\xc0(\xc0'\xc0\n\xc0\t\xc0\x14\xc0\x13\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x007\x00\n\x00\x08\x00\x06\x00\x1d\x00\x17\x00\x18\x00\x0b\x00\x02\x01\x00\x00\r\x00\x14\x00\x12\x06\x01\x06\x03\x04\x01\x05\x01\x02\x01\x04\x03\x05\x03\x02\x03\x02\x02\x00#\x00\x00\x00\x17\x00\x00\xff\x01\x00\x01\x00"

我以为是简单的编码,但是我试过bytemessage.decode()的方法,utf-8,cp437,cp1250,cp1252,latin-1等,我也试过codecs.decode () 与十六进制。没有成功,我不明白这是什么语言

我是 SSL 的新手,所以我想我在这里遗漏了一些明显的东西,但我不知道是什么……

如有任何帮助,我们将不胜感激。

提前致谢!

----这里编辑的是我服务器的代码-----

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 5000)
print ('starting up on %s port %s' % server_address)
sock.bind(server_address)
sock.listen(1)

while True:
     print ( 'waiting for a connection')
     connection, client_address = sock.accept();
     try:
        print( 'connection from', client_address)
        while True:
            data = connection.recv(16)
            print ( 'received "%s"' % data)
            if True:
                 #data2=b'{"timing":{"liveEvents": {"sector": {"dayTime": 1483523892618,"driver": 1,"isValid": false,"participant": "0","sector": 3,"time": -1}}}}'
                 print ('sending data to the client')
                 #connection.sendall(data2)
            else:
                print ( 'no more data from', client_address)
                break

     finally:
        connection.close()
b"\x16\x03\x03...

这是一条 TLS 消息。看起来您的客户端试图与您的服务器通信,但您的服务器无法正确处理它。它不会将数据视为 TLS,而是假定 TLS 是实际的应用程序数据。

查看你的服务器代码,原因很明显:你没有在那里做任何 SSL,即你正在做一个普通的 TCP 套接字。 SSL 不会神奇地出现,因为客户端试图与服务器通信,但您需要正确使用 ssl 模块 wrap_socket 并提供必要的服务器证书和密钥。有关一些简单示例,请参阅 the documentation.

正如@Steffen 提到的,我根本没有处理 SSL,现在我使用 ssl.wrap_socket(sock,certfile='certificat.pem', keyfile='cle.pem', server_side=True)

服务器端的操作需要 pem 中的证书和密钥文件,我使用 SelfSSL7 生成它们,然后使用 OpenSSL 将 pfx 拆分为 2 个 pem 密钥和证书文件

openssl pkcs12 -in yourpfxfile.pfx -nocerts -out privatekey.pem -nodes openssl pkcs12 -in yourpfxfile.pfx -nokeys -out publiccert.pem -nodes

可能不是自签名证书最快的解决方案,因为我现在已经安装了 OpenSSL,但是……

终于收到预期的消息了!!

starting up on localhost port 11000
waiting for a connection
connection from ('127.0.0.1', 60488)
received "b'PING:0::\r\n'"
sending data to the client
received "b'LOGIN:::{"user":"test","password":"test","app":"AppName","app_ver":"1.0.0","protocol":" ","protocol_ver":"1.0.0"}\r\n'"
sending data to the client

再次非常感谢@SteffenUllrich