那天我开始学习python和sockets,我制作了一个简单的客户端服务器应用程序只是为了进行一些测试,它在Python 3.6上可以正常工作,但是在最新版本中却给了我错误。
Server.py
import socket, ssl
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.verify_mode = ssl.CERT_REQUIRED
context.load_cert_chain(certfile="SSL/server.crt", keyfile="SSL/server.key")
context.load_verify_locations("SSL/client.crt")
bindsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
bindsocket.bind(("127.0.0.1", 65405))
bindsocket.listen(10)
while True:
newsocket, fromaddr = bindsocket.accept()
print(newsocket)
connstream = context.wrap_socket(newsocket, server_side=True)
try:
print(connstream.getpeercert())
finally:
connstream.shutdown(socket.SHUT_RDWR)
connstream.close()
Client.py
import ssl, socket
context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
context.load_cert_chain(certfile="SSL/client.crt", keyfile="SSL/client.key")
context.verify_mode = ssl.CERT_REQUIRED
context.check_hostname = True
context.load_verify_locations("SSL/server.crt")
conn = context.wrap_socket(socket.socket(socket.AF_INET, socket.SOCK_STREAM), server_hostname="127.0.0.1")
try:
conn.connect(("127.0.0.1", 65405))
conn.sendall(b"aff")
print(conn.getpeercert())
except:
print("não")
finally:
conn.shutdown(socket.SHUT_RDWR)
conn.close()
错误
Traceback (most recent call last):
File "C:/Users/nicol/Desktop/Kyuu/Bot/Kaori/Python/server.py", line 15, in <module>
connstream = context.wrap_socket(newsocket, server_side=True)
File "C:\Users\nicol\AppData\Local\Programs\Python\Python37\lib\ssl.py", line 412, in wrap_socket
session=session
File "C:\Users\nicol\AppData\Local\Programs\Python\Python37\lib\ssl.py", line 853, in _create
self.do_handshake()
File "C:\Users\nicol\AppData\Local\Programs\Python\Python37\lib\ssl.py", line 1117, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [SSL: SSLV3_ALERT_BAD_CERTIFICATE] sslv3 alert bad certificate (_ssl.c:1056)
编辑1
我尝试使用ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)和ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT),但出现相同的错误。
编辑2
当我在OpenSSL中使用命令“ s_client -connect 127.0.0.1:65405 -cert client.pem -key client.pem -CAfile server.crt”时,效果很好