AES 加密解密

Vibe Prompt

「幫我用 Python 實作 AES-256-GCM 加密與解密:輸入字串與密碼,輸出 base64 編碼的密文。」

實作

from cryptography.fernet import Fernet
import base64, os

# 生成金鑰
key = Fernet.generate_key()
cipher = Fernet(key)

# 加密
text = b"Hello, Vibe Coding! This is a secret message."
encrypted = cipher.encrypt(text)
print(f"加密後: {encrypted.decode()}")

# 解密
decrypted = cipher.decrypt(encrypted)
print(f"解密後: {decrypted.decode()}")

# 手動 AES-256-GCM
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

aes_key = AESGCM.generate_key(bit_length=256)
aesgcm = AESGCM(aes_key)
nonce = os.urandom(12)

ct = aesgcm.encrypt(nonce, b"Secret data", None)
pt = aesgcm.decrypt(nonce, ct, None)
print(f"AES-256-GCM: {pt.decode()}")

應用場景

  • 資料庫欄位加密
  • 設定檔金鑰儲存
  • 通訊加密
  • 檔案加密

會員專屬免費教學

本章節為註冊會員專屬的免費開放內容!請先登入或註冊會員,即可立即解鎖閱讀。

立即登入 / 註冊