我正在尝试在Python 3.4下构建SSL服务器。关键是通过基于JSON数据格式的已定义协议与程序进行通信和交换数据。
因此,我使用了SSL协议中的基本“回显服务器”和客户端,并对它们进行了修改,以查看是否可以交换数据。它可以正常工作,并且发送“ 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()
答案 0 :(得分:1)
b"\x16\x03\x03...
这是TLS消息。看起来您的客户端尝试对服务器说TLS,但服务器无法正确处理它。不是将数据视为TLS,而是假定TLS是实际的应用程序数据。
查看服务器代码的原因很明显:您在那里没有执行任何SSL,即您正在执行普通的TCP套接字。 SSL不会仅仅因为客户端试图与服务器进行SSL对话而神奇地出现,而是您需要正确使用wrap_socket
并使用ssl模块并提供必要的服务器证书和密钥。有关一些简单的示例,请参见the documentation。
答案 1 :(得分:0)
如@Steffen所述,我根本没有处理SSL,现在我使用ssl.wrap_socket(sock,certfile='certificat.pem', keyfile='cle.pem', server_side=True)
服务器端的操作需要使用我通过SelfSSL7生成的pem中的证书和密钥文件,然后使用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