pycryptodome(推薦)
pip install pycryptodome
# 而非舊的 pycrypto(已停維護)
# des_crypto.py
from Crypto.Cipher import DES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
import base64
from typing import Literal
class DESCrypto:
"""DES 加密解密工具類,支持 ECB/CBC、PKCS7、Base64/Hex"""
def __init__(
self,
key: bytes,
mode: Literal['ECB', 'CBC'] = 'CBC',
iv: Optional[bytes] = None,
padding: Literal['pkcs7', 'pkcs5', 'zero', 'none'] = 'pkcs7'
):
"""
:param key: 8 字節密鑰
:param mode: ECB 或 CBC
:param iv: CBC 模式下的 8 字節 IV(ECB 忽略)
:param padding: 填充模式
"""
if len(key) != 8:
raise ValueError("DES 密鑰必須為 8 字節 (64 位)")
self.key = key
self.mode = mode
self.iv = iv
self.padding = padding
if mode == 'CBC':
if iv is None:
self.iv = get_random_bytes(8)
elif len(iv) != 8:
raise ValueError("CBC 模式 IV 必須為 8 字節")
def _get_cipher(self, iv: Optional[bytes] = None):
if self.mode == 'ECB':
return DES.new(self.key, DES.MODE_ECB)
else:
return DES.new(self.key, DES.MODE_CBC, iv or self.iv)
def _apply_padding(self, data: bytes) -> bytes:
if self.padding in ('pkcs7', 'pkcs5'):
return pad(data, DES.block_size, style='pkcs7')
elif self.padding == 'zero':
# 零填充到 8 字節倍數
pad_len = DES.block_size - (len(data) % DES.block_size)
return data + b'\x00' * pad_len
elif self.padding == 'none':
if len(data) % DES.block_size != 0:
raise ValueError("無填充模式下數據長度必須是 8 字節倍數")
return data
else:
raise ValueError(f"未知填充模式: {self.padding}")
def _remove_padding(self, data: bytes) -> bytes:
if self.padding in ('pkcs7', 'pkcs5'):
return unpad(data, DES.block_size, style='pkcs7')
elif self.padding == 'zero':
return data.rstrip(b'\x00')
elif self.padding == 'none':
return data
else:
raise ValueError(f"未知填充模式: {self.padding}")
def encrypt(self, plaintext: str | bytes, encoding: str = 'utf-8', output: Literal['base64', 'hex', 'bytes'] = 'base64') -> str | bytes:
"""加密"""
if isinstance(plaintext, str):
data = plaintext.encode(encoding)
else:
data = plaintext
padded = self._apply_padding(data)
cipher = self._get_cipher()
ciphertext = cipher.encrypt(padded)
if output == 'base64':
return base64.b64encode(ciphertext).decode('ascii')
elif output == 'hex':
return ciphertext.hex()
else:
return ciphertext
def decrypt(self, ciphertext: str | bytes, encoding: str = 'utf-8', input_format: Literal['base64', 'hex', 'bytes'] = 'base64') -> str:
"""解密"""
if isinstance(ciphertext, str):
if input_format == 'base64':
data = base64.b64decode(ciphertext)
elif input_format == 'hex':
data = bytes.fromhex(ciphertext)
else:
raise ValueError("字符串輸入需指定 input_format")
else:
data = ciphertext
cipher = self._get_cipher()
decrypted = cipher.decrypt(data)
unpadded = self._remove_padding(decrypted)
return unpadded.decode(encoding)
# ========== 使用示例 ==========
if __name__ == '__main__':
# 8 字節密鑰
key = b'12345678' # 實際應從安全配置讀取,不可硬編碼
# 1. ECB 模式(不需 IV,不安全,僅用於兼容舊系統)
ecb = DESCrypto(key, mode='ECB', padding='pkcs7')
text = "Hello DES ECB Mode!"
enc = ecb.encrypt(text, output='base64')
dec = ecb.decrypt(enc, input_format='base64')
print(f"ECB: {text} -> {enc} -> {dec}")
# 2. CBC 模式(推薦,需 IV)
iv = b'abcdefgh' # 8 字節,實際應隨機生成並與密文一起傳輸
cbc = DESCrypto(key, mode='CBC', iv=iv, padding='pkcs7')
text = "Hello DES CBC Mode! 中文測試"
enc = cbc.encrypt(text, output='base64')
dec = cbc.decrypt(enc, input_format='base64')
print(f"CBC: {text} -> {enc} -> {dec}")
# 3. 異語言互操作:Java/Go/JS 端使用相同 Key/IV/Padding/Mode 即可互通
原文提供了 S 盒、置換表等完整表格,可按 FIPS 46-3 標準純 Python 實現。這裡給出框架,核心輪函數參考標準算法:
# des_manual.py — 純 Python DES 實現(教學/嵌入式無依賴環境)
# 完整實現包含:IP 初始置換、16 輪 Feistel 網絡 (E擴展、S盒、P置換)、FP 逆置換、密鑰調度 (PC-1, PC-2, 循環左移)
# 代碼量較大(~300 行),此處給出核心結構:
# S 盒 (8 個 4x16 表)
S_BOXES = [
[[14,4,13,1,2,15,11,8,3,10,6,12,5,9,0,7], ...], # S1
# ... S2~S8 完整表見原文或 FIPS 46-3
]
# 置換表
IP_TABLE = [58,50,42,34,26,18,10,2, 60,52,44,36,28,20,12,4, ...]
FP_TABLE = [40,8,48,16,56,24,64,32, 39,7,47,15,55,23,63,31, ...]
E_TABLE = [32,1,2,3,4,5, 4,5,6,7,8,9, 8,9,10,11,12,13, ...]
P_TABLE = [16,7,20,21,29,12,28,17, 1,15,23,26,5,18,31,10, ...]
PC1_TABLE = [57,49,41,33,25,17,9,1, 58,50,42,34,26,18,10,2, ...]
PC2_TABLE = [14,17,11,24,1,5,3,28, 15,6,21,10,23,19,12,4, ...]
SHIFT_SCHEDULE = [1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1]
def _permute(block: int, table: list[int], in_bits: int, out_bits: int) -> int:
"""通用位置換"""
result = 0
for i, pos in enumerate(table):
bit = (block >> (in_bits - pos)) & 1
result |= bit << (out_bits - 1 - i)
return result
def _feistel(round_key: int, right: int) -> int:
"""單輪 Feistel 函數: E擴展 -> XOR密鑰 -> S盒替換 -> P置換"""
expanded = _permute(right, E_TABLE, 32, 48)
xored = expanded ^ round_key
# S 盒替換 (8 組 6bit->4bit)
s_out = 0
for i in range(8):
six_bits = (xored >> (42 - 6*i)) & 0x3F
row = ((six_bits & 0x20) >> 4) | (six_bits & 0x01)
col = (six_bits >> 1) & 0x0F
s_out = (s_out << 4) | S_BOXES[i][row][col]
return _permute(s_out, P_TABLE, 32, 32)
def _key_schedule(key_64: int) -> list[int]:
"""生成 16 個 48 位子密鑰"""
key_56 = _permute(key_64, PC1_TABLE, 64, 56)
c = (key_56 >> 28) & 0xFFFFFFF
d = key_56 & 0xFFFFFFF
subkeys = []
for shift in SHIFT_SCHEDULE:
c = ((c << shift) | (c >> (28 - shift))) & 0xFFFFFFF
d = ((d << shift) | (d >> (28 - shift))) & 0xFFFFFFF
cd = (c << 28) | d
subkeys.append(_permute(cd, PC2_TABLE, 56, 48))
return subkeys
def des_encrypt_block(block: bytes, key: bytes) -> bytes:
"""加密單個 8 字節塊 (ECB)"""
block_int = int.from_bytes(block, 'big')
key_int = int.from_bytes(key, 'big')
# IP
block_int = _permute(block_int, IP_TABLE, 64, 64)
left = (block_int >> 32) & 0xFFFFFFFF
right = block_int & 0xFFFFFFFF
subkeys = _key_schedule(key_int)
for k in subkeys:
left, right = right, left ^ _feistel(k, right)
# FP (注意合併順序: right||left)
combined = (right << 32) | left
result = _permute(combined, FP_TABLE, 64, 64)
return result.to_bytes(8, 'big')
# 完整 ECB/CBC + Padding 封裝略...
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import base64, os
def aes_gcm_encrypt(key: bytes, plaintext: bytes, associated_data: bytes = b'') -> tuple[bytes, bytes, bytes]:
"""AES-256-GCM 認證加密,返回 (nonce, ciphertext, tag)"""
cipher = AES.new(key, AES.MODE_GCM)
cipher.update(associated_data)
ciphertext, tag = cipher.encrypt_and_digest(pad(plaintext, AES.block_size))
return cipher.nonce, ciphertext, tag
def aes_gcm_decrypt(key: bytes, nonce: bytes, ciphertext: bytes, tag: bytes, associated_data: bytes = b'') -> bytes:
cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
cipher.update(associated_data)
plaintext = cipher.decrypt_and_verify(ciphertext, tag)
return unpad(plaintext, AES.block_size)
# 使用
key = os.urandom(32) # 256-bit
nonce, ct, tag = aes_gcm_encrypt(key, b"Sensitive Data")
pt = aes_gcm_decrypt(key, nonce, ct, tag)
print(pt) # b'Sensitive Data'
Python 實現 DES 加解密: