Contents

[Python]使用pyDes.py動態加密解密

DES(Data Encryption Standard)是一種對稱式加密演算法,由 IBM 於 1970 年代設計,曾是美國聯邦標準加密算法。pyDes 是一個純 Python 實作的 DES/3DES 函式庫,不依賴任何外部 C 函式庫。

⚠️ 重要警告:DES 金鑰長度只有 56 位元,現代電腦可在短時間內暴力破解。生產環境請使用 AES-256,不要使用 DES 處理敏感資料。

DES 加密基本概念

  • 對稱式加密:加密和解密使用相同的金鑰
  • 金鑰長度:56 位元(8 bytes,但有效位元為 56 bit)
  • 區塊大小:64 位元(8 bytes),資料長度必須為 8 的倍數
  • CBC 模式:Cipher Block Chaining,每個區塊的加密依賴前一區塊的密文,需要 IV(初始向量)
  • Padding:若資料長度不是 8 的倍數,需要填充(PKCS5)

安裝 pyDes

1
pip install pyDes

Python 3 相容的使用範例

原始程式碼使用 Python 2 的 print 語法,以下為更新至 Python 3 的版本:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
from pyDes import des, CBC, PAD_PKCS5
import base64
import random

# 準備要加密的資料(必須是 bytes 型別)
data = str(random.random()) + "|" + "加密內容"

# 建立 DES 物件
# 金鑰:必須為 8 bytes
# 模式:CBC
# IV:必須為 8 bytes
# padmode:自動填充模式
k = des(b'DESCRYPT', CBC, b'12345675', pad=None, padmode=PAD_PKCS5)

# 加密(輸入必須是 bytes)
encrypted = k.encrypt(data.encode('utf-8'))
print("Encrypted:", base64.b64encode(encrypted).decode())

# 解密
decrypted = k.decrypt(encrypted)
print("Decrypted:", decrypted.decode('utf-8'))

3DES(Triple DES)

pyDes 也支援 3DES,金鑰長度為 24 bytes,安全性比 DES 強但仍不推薦用於新系統:

1
2
3
4
5
6
7
8
9
from pyDes import triple_des, CBC, PAD_PKCS5

# 3DES 金鑰必須是 16 或 24 bytes
k = triple_des(b'A24ByteKeyForTripleDES!!', CBC, b'InitVect', padmode=PAD_PKCS5)

data = b"Secret message"
encrypted = k.encrypt(data)
print("Encrypted:", encrypted.hex())
print("Decrypted:", k.decrypt(encrypted))

現代替代方案:使用 AES 加密

AES(Advanced Encryption Standard)是目前最廣泛使用的對稱式加密演算法,金鑰長度支援 128/192/256 位元,安全性遠優於 DES。

安裝:

1
pip install pycryptodome

使用 AES-256-CBC 加密:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
import base64

def encrypt_aes(plaintext: str, key: bytes) -> str:
    """AES-256-CBC 加密,回傳 Base64 編碼的密文"""
    iv = get_random_bytes(16)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    ciphertext = cipher.encrypt(pad(plaintext.encode('utf-8'), AES.block_size))
    return base64.b64encode(iv + ciphertext).decode()

def decrypt_aes(ciphertext_b64: str, key: bytes) -> str:
    """AES-256-CBC 解密"""
    data = base64.b64decode(ciphertext_b64)
    iv = data[:16]
    ciphertext = data[16:]
    cipher = AES.new(key, AES.MODE_CBC, iv)
    return unpad(cipher.decrypt(ciphertext), AES.block_size).decode('utf-8')

# 使用範例(金鑰必須是 32 bytes = AES-256)
key = get_random_bytes(32)
message = "這是要加密的訊息"

encrypted = encrypt_aes(message, key)
print("Encrypted:", encrypted)

decrypted = decrypt_aes(encrypted, key)
print("Decrypted:", decrypted)

加密方案比較

特性 DES 3DES AES-128 AES-256
金鑰長度 56 bit 112/168 bit 128 bit 256 bit
區塊大小 64 bit 64 bit 128 bit 128 bit
安全性 ❌ 已破解 ⚠️ 不建議 ✅ 安全 ✅ 非常安全
速度 很慢
建議 禁止使用 禁止使用 可用 推薦

參考資料