Báo cáo thí nghiệm Python: Triển khai kết nối TCP và mã hóa dữ liệu

1. Nội dung thí nghiệm

Xây dựng ứng dụng client-server sử dụng giao thức TCP, trong đó:

  • Server lắng nghe kết nối trên cổng 8080
  • Client kết nối và trao đổi dữ liệu với server
  • Áp dụng mã hóa Fernet cho luồng dữ liệu
  • Thực hiện thao tác đọc/ghi file trong quá trình truyền nhận

2. Triển khai hệ thống

Server xử lý kết nối

Hiện code

import socket
from cryptography.fernet import Fernet

# Cấu hình kết nối
HOST = '127.0.0.1'
PORT = 8080

# Tạo socket server
server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_sock.bind((HOST, PORT))
server_sock.listen(1)
print(f"Server đang lắng nghe trên {HOST}:{PORT}")

# Chấp nhận kết nối
conn, addr = server_sock.accept()
print(f"Kết nối từ {addr}")

# Tạo khóa mã hóa
key = Fernet.generate_key()
cipher = Fernet(key)
print(f"Khóa mã hóa: {key.decode()}")

try:
    # Nhận dữ liệu mã hóa
    encrypted_data = conn.recv(1024)
    # Giải mã dữ liệu
    decrypted = cipher.decrypt(encrypted_data).decode()
    
    # Lưu dữ liệu vào file
    with open('data_output.txt', 'w') as f:
        f.write(decrypted)
    print("Đã lưu dữ liệu giải mã vào file")
    
finally:
    conn.close()
    server_sock.close()

Client kết nối và gửi dữ liệu

Hiện code

import socket
from cryptography.fernet import Fernet

# Cấu hình kết nối
HOST = '127.0.0.1'
PORT = 8080

# Tạo socket client
client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_sock.connect((HOST, PORT))

# Nhập khóa từ server
key = input("Nhập khóa mã hóa từ server: ").encode()
cipher = Fernet(key)

try:
    # Đọc dữ liệu từ file
    with open('data_input.txt', 'r') as f:
        plaintext = f.read()
    
    # Mã hóa dữ liệu
    encrypted = cipher.encrypt(plaintext.encode())
    
    # Gửi dữ liệu qua socket
    client_sock.sendall(encrypted)
    print("Đã gửi dữ liệu mã hóa đến server")
    
finally:
    client_sock.close()

3. Kết quả đạt được

  • Thiết lập kết nối TCP thành công giữa client và server
  • Thực hiện mã hóa/giải mã dữ liệu bằng Fernet
  • Hoàn thành thao tác đọc file đầu vào và ghi file đầu ra
  • Triển khai thành công trên môi trường hỗn hợp Windows/Linux

4. Vấn đề gặp phải

Lỗi import thư viện cryptography:
Khắc phục bằng cách cài đặt lại thư viện thông qua pip với lệnh: pip install cryptography. Đảm bảo phiên bản Python tương thích với thư viện (>=3.6).

Thẻ: python socket TCP Fernet xử lý tệp

Đăng vào ngày 11 tháng 6 lúc 04:21