1. 程式人生 > 實用技巧 >python使用ssl的單向認證和雙向認證的客戶端程式碼

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)

注:python2.7.9版本後支援對證書加密