Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีเข้ารหัสและถอดรหัสข้อมูลใน Python ด้วย Cryptography Fernet

บทนำ

Cryptography คือการแปลง plaintext → ciphertext (encrypt) และกลับมา (decrypt) ใช้ Fernet (symmetric encryption) จาก package cryptography

การติดตั้ง

pip install cryptography

ขั้นตอนหลัก

1. Generate Key

from cryptography.fernet import Fernet
key = Fernet.generate_key()
f = Fernet(key)
print(key.decode())  # แสดง key เป็น string

2. Encrypt

encrypted_data = f.encrypt(b"This message is being encrypted and cannot be seen!")
print(encrypted_data)

3. Decrypt

decrypted_data = f.decrypt(encrypted_data)
print(decrypted_data.decode())  # bytes → string

โค้ดตัวอย่างครบถ้วน

from cryptography.fernet import Fernet
key = Fernet.generate_key()
print("Key:", key.decode())
f = Fernet(key)
encrypted_data = f.encrypt(b"This message is being encrypted and cannot be seen!")
print("After encryption:", encrypted_data)
decrypted_data = f.decrypt(encrypted_data)
print("After decryption:", decrypted_data.decode())

ผลลัพธ์

Key: u4dM7xw8sNNU3Rm_lwDbixudWSeaM0Z4TTDdQNKsouI=
After encryption: b'gAAAAABgIL3_qbfM_oMgQn653gpk6a7hqxXiR0dl0vrmOmqnr5b6MqrsjGkK1IknxMLLtOCq6_YlX4x3nBedbZqtCqy4os55pttrl-pBO6-dJf6kVP50IpIaKSXbpAsuWl4h_2o_E-4YEqZ5kkgxWrwnqojmkMyuSQ=='
After decryption: This message is being encrypted and cannot be seen!

คำอธิบาย

  • Fernet ใช้ AES-128-CBC + HMAC-SHA256 (authenticated encryption)
  • Key ต้องเก็บไว้ปลอดภัย ใครมี key ก็ decrypt ได้
  • Input ต้องเป็น bytes (ใช้ b"..." หรือ .encode())
  • Output encrypt เป็น bytes (URL-safe base64 encoded)
  • Decrypt คืน bytes → .decode() ได้ string กลับ

การนำ Key ไปใช้ใหม่

f = Fernet(b"saved_key_string")  # load key ที่เคย generate และเก็บไว้

กรณีใช้งาน

- เข้ารหัส password/config ก่อนเก็บใน database
- Secure messaging
- Token signing (แต่แนะนำ JWT สำหรับเรื่องนี้)

เอกสาร: https://pypi.org/project/cryptography/