【发布时间】:2021-12-18 11:50:32
【问题描述】:
如何使用 Python 创建 SSL 套接字服务器? 我从一个站点获取了 Ssl 文件,并且想在另一台服务器上使用它们。我可以这样做吗?
我的 SSL 文件:
ca.pem:证书颁发机构包
cert.crt:证书
key.key:私钥
我的服务器 Python 代码:
from socket import *
import hashlib,base64,ssl,datetime
Socket = socket(2,1)
Socket.bind((IP,Port))
Socket.listen()
print("Service Started on "+IP+":"+str(Port))
while True:
Connection,Address = Socket.accept()
Secure_Connection = ssl.wrap_socket(Connection, server_side=True, ca_certs="ca.pem", certfile="cert.crt", keyfile="key.key", cert_reqs=ssl.CERT_REQUIRED, ssl_version=ssl.PROTOCOL_TLSv1_2);
# Get certificate from the client
Client_Cert = Secure_Connection.getpeercert();
CLT_Subject = dict(item[0] for item in Client_Cert['subject']);
CLT_Common_Name = CLT_Subject['commonName'];
# Check the client certificate bears the expected name as per server's policy
if not Client_Cert:
raise Exception("Unable to get the certificate from the client");
if CLT_Common_Name != 'DemoClt':
raise Exception("Incorrect common name in client certificate");
# Check time validity of the client certificate
T1 = ssl.cert_time_to_seconds(Client_Cert['notBefore']);
T2 = ssl.cert_time_to_seconds(Client_Cert['notAfter']);
TS = time.time();
if TS < T1:
raise Exception("Client certificate not yet active");
if TS > T2:
raise Exception("Expired client certificate");
# Send current server time to the client
Time = "%s"%datetime.datetime.now();
Secure_Connection.send(Time.encode());
print("Securely sent %s to %s"%(Time,Address[0]));
# Close the connection to the client
Secure_Connection.close();
但我得到了这个 SSL 错误:
Secure_Connection = ssl.wrap_socket(Connection, server_side=True, ca_certs="ca.pem", certfile="cert.crt", keyfile="key.key", cert_reqs=ssl.CERT_REQUIRED, ssl_version=ssl.PROTOCOL_TLSv1_2);
File "C:\Program Files\Python39\lib\ssl.py", line 1405, in wrap_socket
return context.wrap_socket(
File "C:\Program Files\Python39\lib\ssl.py", line 500, in wrap_socket
return self.sslsocket_class._create(
File "C:\Program Files\Python39\lib\ssl.py", line 1040, in _create
self.do_handshake()
File "C:\Program Files\Python39\lib\ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [SSL: SSLV3_ALERT_CERTIFICATE_UNKNOWN] sslv3 alert certificate unknown (_ssl.c:1129)
这个错误的原因是什么?
【问题讨论】:
标签: python sockets ssl websocket