萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 實現 DES 加密解密完整指南(含 CBC/ECB、Padding、Base64)

DES 基礎知識

  • 分組長度:64 位(8 字節)
  • 密鑰長度:64 位(含 8 位校驗位,有效 56 位)
  • 模式:ECB(無 IV,不安全)、CBC(需 IV,推薦)、CFB/OFB/CTR(流模式)
  • 填充:PKCS#7(標準)、PKCS#5(同 8 字節塊)、Zero Padding、ISO 10126
  • 安全性:DES 已被暴力破解,**生產環境請用 AES-256-GCM**。本文僅供維護舊系統、教學、互操作參考。

依賴: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 即可互通

手動實現 DES(教學用,無第三方依賴)

原文提供了 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 封裝略...

關鍵工程提示

  1. 密鑰管理:切勿硬編碼密鑰。使用 KMS、環境變量、密鑰派生函數(PBKDF2/Scrypt/Argon2)從口令派生。
  2. IV 唯一性:CBC 模式下,同一密鑰**每次加密必須使用隨機 IV**,IV 無需保密,可與密文一起傳輸(如 `IV || Ciphertext`)。
  3. 填充一致性:雙端必須約定相同填充模式(PKCS#7 最通用)。
  4. 完整性保護:DES 本身無完整性校驗,**必須配合 HMAC-SHA256** 或改用 **AES-GCM**(自帶認證)。
  5. 避免 ECB:相同明文塊產生相同密文塊,洩露模式信息。

從 DES 遷移到 AES 的建議


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 加解密:

  • **生產代碼**:直接用 `pycryptodome` 的 `Crypto.Cipher.DES`,封裝模式/填充/編碼細節。
  • **教學/無依賴**:參考 FIPS 46-3 實現 IP、Feistel、S盒、密鑰調度,理解分組密碼核心結構。
  • **安全警示**:DES 已淘汰,**新系統一律使用 AES-GCM 或 ChaCha20-Poly1305**,並妥善管理密鑰、Nonce、關聯數據。
copyright © 萬盛學電腦網 all rights reserved