python使用ssl的单向认证和双向认证的客户端代码
参考文档:https://blog.csdn.net/wuliganggang/article/details/78428866
实现:
1. 单向认证:client需要一个ca.crt,校验服务器的合法性。
def connectSSL(self, _tcp_ip, _tcp_port, _ca_certs=\'ca.crt\'):s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sk = ssl.wrap_socket(s, cert_reqs=ssl.CERT_REQUIRED, ca_certs=_ca_certs)
try:
sk.connect((_tcp_ip, _tcp_port))
except Exception, e:
logging.error(str(e))
exit(1)
2. 双向认证:client对server进行校验,同时server也对client进行校验,client需要client.key 、client.crt 、ca.crt
def connectSSL(self, _tcp_ip=\'192.168.1.100\', _tcp_port=10000, _keyfile=\'user.key\', _certfile=\'user.pem\', _ca_certs=\'ca.crt\'):s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sk = ssl.wrap_socket(s, keyfile=_keyfile, certfile=_certfile, cert_reqs=ssl.CERT_REQUIRED, ca_certs=_ca_certs)
try:
sk.connect((_tcp_ip, _tcp_port))
print "cert type: " , sk.getpeercert()
except Exception, e:
logging.error(str(e))
exit(1)
3. 不做认证
def connectSSL(self, _tcp_ip=\'192.168.1.100\', _tcp_port=10000):s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sk = ssl.wrap_socket(s, cert_reqs=ssl.CERT_NONE)
try:
sk.connect((_tcp_ip, _tcp_port))
print "cert type: " , sk.getpeercert()
except Exception, e:
logging.error(str(e))
exit(1)
注:python2.7.9版本后支持对证书加密
补充:
安装
1. 使用pip安装:
pip install pyopenssl
2. 下载安装包安装:
pyopenssl下载:https://launchpad.net/pyopenssl/+download
windows直接用.exe安装
cryptography下载:https://pypi.org/project/cryptography/0.2.2/#files
执行 pip install *.whl安装
以上是 python使用ssl的单向认证和双向认证的客户端代码 的全部内容, 来源链接: utcz.com/z/387461.html