SSL:CERTIFICATE_VERIFY_FAILED证书验证失败:自签名证书(_ssl.c:1076)Python ssl和套接字

时间:2020-06-03 21:46:42

标签: python python-3.x sockets ssl

我一直收到以下错误

    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()

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

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

0 个答案:

没有答案