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()}")

應用場景

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

---

## 關鍵要點

### AES 三種金鑰長度

| 版本 | 金鑰長度 | 回合數 | 安全性 |
|:----:|:--------:|:------:|:------:|
| AES-128 | 128 bits | 10 | ✅ 安全 |
| AES-192 | 192 bits | 12 | ✅ 更安全 |
| AES-256 | 256 bits | 14 | ✅ **最高安全**(建議) |

### 加密模式比較

| 模式 | 需要 IV | 平行化 | 認證加密 | 建議 |
|:----:|:-------:|:------:|:--------:|:----:|
| ECB | ❌ | ✅ | ❌ | ❌ 不安全 |
| CBC | ✅ | ❌ | ❌ | ⚠️ 通用但無認證 |
| CTR | ✅ | ✅ | ❌ | ✅ 串流加密 |
| GCM | ✅ | ✅ | ✅ | ✅ **建議使用** |
| CCM | ✅ | ❌ | ✅ | ⚠️ IoT 裝置 |

> ⚠️ **ECB 模式不應該在任何真實專案中使用**,因為同樣的明文會產生同樣的密文。

### Python 實作範例

```python
from cryptography.fernet import Fernet

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

# 加密
encrypted = cipher.encrypt(b"Hello, World!")

# 解密
decrypted = cipher.decrypt(encrypted)
print(decrypted.decode())  # Hello, World!


AES:現代加密的黃金標準

AES(Advanced Encryption Standard)是全世界使用最廣泛的對稱加密演算法。你的 Wi-Fi 密碼、HTTPS 連線、WhatsApp 訊息——底層都是 AES。

AES 為什麼安全?

AES 不是靠「沒人知道這個演算法」來保護資料(那是 Security Through Obscurity)。AES 的演算法是完全公開的——任何人都可以研究它。它的安全性來自金鑰的長度

| AES 變體 | 金鑰長度 | 暴力破解時間(2026 年估計) | |:--------|:-------|:------------------------| | AES-128 | 128 bits | ~10¹⁸ 年 | | AES-256 | 256 bits | ~10³⁶ 年 |

加密模式也很重要

| 模式 | 特性 | 適合場景 | |:----|:----|:--------| | ECB | 相同明文產生相同密文 | ❌ 不安全,不要用 | | CBC | 需要 IV,平行解密 | ✅ 檔案加密 | | GCM | 內建完整性驗證 | ✅ 網路通訊(TLS 使用) |

實戰範例

from cryptography.fernet import Fernet

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

# 加密
encrypted = cipher.encrypt(b"Hello World")

# 解密
decrypted = cipher.decrypt(encrypted)
print(decrypted.decode())  # Hello World

下一章預告:非對稱加密與 RSA

AES 是對稱加密——加密和解密用同一把金鑰。下一章的 RSA 是非對稱加密——有公鑰和私鑰兩把。這讓金鑰交換變成可能,也是 HTTPS 的基礎。

會員專屬免費教學

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

立即登入 / 註冊