在Python中實(shí)現(xiàn)網(wǎng)絡(luò)編程的數(shù)據(jù)加密傳輸,通常需要以下幾個(gè)步驟:
下面是一個(gè)簡(jiǎn)單的示例,使用Python的socket
庫(kù)進(jìn)行網(wǎng)絡(luò)編程,并使用cryptography
庫(kù)進(jìn)行AES加密和解密。
首先,你需要安裝cryptography
庫(kù):
pip install cryptography
import socket
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
import base64
import os
# 生成密鑰
def generate_key(password, salt):
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=100000,
)
return base64.urlsafe_b64encode(kdf.derive(password))
# 加密數(shù)據(jù)
def encrypt_message(message, key):
f = Fernet(key)
encrypted_message = f.encrypt(message.encode())
return encrypted_message
# 解密數(shù)據(jù)
def decrypt_message(encrypted_message, key):
f = Fernet(key)
decrypted_message = f.decrypt(encrypted_message).decode()
return decrypted_message
# 創(chuàng)建服務(wù)器
def start_server(host='0.0.0.0', port=5000):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen(5)
print(f"Server listening on {host}:{port}")
while True:
client_socket, addr = server_socket.accept()
print(f"Connection from {addr}")
# 獲取客戶端密碼
password = client_socket.recv(1024).decode().strip()
# 生成鹽
salt = os.urandom(16)
key = generate_key(password.encode(), salt)
# 接收消息
encrypted_message = client_socket.recv(1024)
# 解密消息
decrypted_message = decrypt_message(encrypted_message, key)
print(f"Received message: {decrypted_message}")
# 發(fā)送響應(yīng)
response = "Message received and decrypted successfully."
client_socket.send(response.encode())
client_socket.close()
# 創(chuàng)建客戶端
def start_client(host='127.0.0.1', port=5000):
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((host, port))
# 發(fā)送密碼
password = input("Enter password: ")
client_socket.send(password.encode())
# 接收加密消息
encrypted_message = client_socket.recv(1024)
# 解密消息
key = generate_key(password.encode(), salt) # 這里應(yīng)該使用接收到的鹽
decrypted_message = decrypt_message(encrypted_message, key)
print(f"Received message: {decrypted_message}")
client_socket.close()
if __name__ == "__main__":
import threading
server_thread = threading.Thread(target=start_server)
client_thread = threading.Thread(target=start_client)
server_thread.start()
client_thread.start()
server_thread.join()
client_thread.join()
cryptography
庫(kù)中的Fernet
類進(jìn)行AES加密和解密。請(qǐng)注意,這個(gè)示例僅用于演示目的,實(shí)際應(yīng)用中可能需要更多的安全措施,如密鑰的安全存儲(chǔ)和管理、更復(fù)雜的加密算法等。