如何通過Python3和ssl實現加密通信功能
一、說明
1. python標準庫ssl可實現加密通信
2. ssl庫底層使用openssl,做了面向對像化改造和簡化,但還是可以明顯看出openssl的痕跡
3. 本文先給出python實現的socket通信,在此基礎上再給出ssl通信以便讀者更方便地看到socket和ssl在python編程中的區別
4. 說到ssl很多人都會想到https,但本質而言ssl是在傳輸層和應用層之間新插入的一個層,根據不同層無關原則ssl和https并沒有任何綁定關系,ssl之上完全可以是其他任何應用層協議(比如pop/imap/telnet等等)
二、程序實現
2.1 socket通信實現
客戶端代碼:
import socketclass client_class: def send_hello(self): # 與服務端建立連接 client_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) client_socket.connect((’127.0.0.1’,9999)) # 向服務端發送消息 msg = 'do i connect with server ?'.encode('utf-8') client_socket.send(msg) # 接收服務端返回的消息 msg = client_socket.recv(1024).decode(’utf-8’) print(f'receive msg from server : {msg}') client_socket.close()if __name__ == '__main__': client = client_class() client.send_hello()
服務端代碼:
import socketclass server_class : def build_listen(self): # 監聽端口 server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) server_socket.bind((’127.0.0.1’,9999)) server_socket.listen(5) while True: # 接收客戶端連接 client_socket, addr = server_socket.accept() # 接收客戶端信息 msg = client_socket.recv(1024).decode('utf-8') print(f'receive msg from client {addr}:{msg}') # 向客戶端發送信息 msg = f'yes , you have client_socketect with server.rn'.encode('utf-8') client_socket.send(msg) client_socket.close()if __name__ == '__main__': server = server_class() server.build_listen()
2.2 ssl通信實現
客戶端代碼:
import socketimport sslclass client_ssl: def send_hello(self,): # 生成SSL上下文 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) # 加載信任根證書 context.load_verify_locations(’cert/ca.crt’) # 與服務端建立socket連接 with socket.create_connection((’127.0.0.1’, 9443)) as sock: # 將socket打包成SSL socket # 一定要注意的是這里的server_hostname不是指服務端IP,而是指服務端證書中設置的CN,我這里正好設置成127.0.1而已 with context.wrap_socket(sock, server_hostname=’127.0.0.1’) as ssock: # 向服務端發送信息 msg = 'do i connect with server ?'.encode('utf-8') ssock.send(msg) # 接收服務端返回的信息 msg = ssock.recv(1024).decode('utf-8') print(f'receive msg from server : {msg}') ssock.close()if __name__ == '__main__': client = client_ssl() client.send_hello()
服務端代碼:
import socketimport sslclass server_ssl: def build_listen(self): # 生成SSL上下文 context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) # 加載服務器所用證書和私鑰 context.load_cert_chain(’cert/server.crt’, ’cert/server_rsa_private.pem.unsecure’) # 監聽端口 with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock: sock.bind((’127.0.0.1’, 9443)) sock.listen(5) # 將socket打包成SSL socket with context.wrap_socket(sock, server_side=True) as ssock: while True: # 接收客戶端連接 client_socket, addr = ssock.accept() # 接收客戶端信息 msg = client_socket.recv(1024).decode('utf-8') print(f'receive msg from client {addr}:{msg}') # 向客戶端發送信息 msg = f'yes , you have client_socketect with server.rn'.encode('utf-8') client_socket.send(msg) client_socket.close()if __name__ == '__main__': server = server_ssl() server.build_listen()
三、運行結果
當前項目結構如圖所示,證書生成可參考:openssl實現雙向認證教程
3.1 socket通信運行結果
客戶端:
服務端:
3.2 ssl通信運行結果
客戶端:
服務端:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: