SSL:CERTIFICATE\u VERIFY\u FAILED证书验证失败:自签名证书(\u SSL.c:1076)Python SSL和套接字

2024-09-24 00:28:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直收到以下错误

self.ssock = context.wrap_socket(self.clientSocket, server_hostname=destinationAddress) File "C:\Users\HIFI\AppData\Local\Programs\Python\Python37-32\lib\ssl.py", line 423, in wrap_socket session=session File "C:\Users\HIFI\AppData\Local\Programs\Python\Python37-32\lib\ssl.py", line 870, in _create self.do_handshake() File "C:\Users\HIFI\AppData\Local\Programs\Python\Python37-32\lib\ssl.py", line 1139, in do_handshake self._sslobj.do_handshake() ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate (_ssl.c:1076)

我不明白为什么会这样。我猜这与我的证书有关。我已经尝试了下面的解决方案。有几篇论坛帖子都建议使用它,但不应该使用,因为它会关闭SSL

#To fix certificate issue try: _create_unverified_https_context = ssl._create_unverified_context except AttributeError: # Legacy Python that doesn't verify HTTPS certificates by default pass else: # Handle target environment that doesn't support HTTPS verification ssl._create_default_https_context = _create_unverified_https_context

我使用以下命令生成了自己的证书

openssl req -new -newkey rsa:4096 -nodes -keyout certificates.key -out certificates.csr openssl x509 -req -sha256 -days 365 -in certificates.csr -signkey certificates.key -out certificates.pem

它生成了以下证书:

certificates.csr certificates.key (used in code) certificates.pem (used in code)

然后,我在以下服务器代码中使用这些证书:

context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) context.load_cert_chain(pemPath,keyPath) #Initialize the Socket that will be listening for incoming connections theSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM,0) theSocket.settimeout(None) theSocket.bind(('',port)) theSocket.listen(numBufferedConnections) ssock = context.wrap_socket(theSocket, server_side=True)

然后,我使用以下代码从客户端连接到此服务器:

try: _create_unverified_https_context = ssl._create_unverified_context except AttributeError: #Legacy Python that doesn't verify HTTPS certificates by default pass else: # Handle target environment that doesn't support HTTPS verification ssl._create_default_https_context = _create_unverified_https_context context = ssl.create_default_context() self.clientSocket = socket.create_connection((destinationAddress,destinationPort), None) self.ssock = context.wrap_socket(self.clientSocket, server_hostname=destinationAddress) ssockVersion = self.ssock.version()

wrap_socket()是代码失败并显示上述错误消息的行

请注意,其他论坛帖子指出关闭验证,这在这种情况下是不可接受的,并且违背了使用ssl的目的


Tags: inhttpsselfdefaultsslthatcreatecontext