萬盛學電腦網

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

Python 實作 RC4 流加密演算法:擴充 16×16 S-Box、32 Bytes 金鑰、檔案級加解密

演算法特色

  • 擴充 S-Box:標準 RC4 使用 256-byte S-Box,本實作擴充至 65536 (16×16) entries,每個 entry 為 2-byte (unsigned short),大幅提升週期長度。
  • 32-byte 金鑰:256-bit 金鑰空間,抗暴力破解。
  • 動態金鑰更新:每區塊加密後自動演進金鑰,達到「一次一鑰」效果。
  • CRC32 完整性驗證:每區塊附加 CRC32,防篡改。
  • 跨平台互通:Python 與 C++ 實作可互解。

核心加密邏輯 (Python 3)


import struct, sys, os, binascii

N = 65536  # 16*16*256 = 65536

def rc4_encrypt(key: list, keylen: int, plaintext_shorts: list, datalen: int) -> bytes:
    """RC4 核心:輸入 short 陣列,輸出加密後 bytes"""
    # KSA: Key Scheduling Algorithm
    S = list(range(N))
    j = 0
    for i in range(N):
        j = (j + S[i] + key[i % keylen]) % N
        S[i], S[j] = S[j], S[i]

    # PRGA: Pseudo-Random Generation Algorithm
    i = j = 0
    out = bytearray()
    for x in range(datalen):
        i = (i + 1) % N
        j = (j + S[i]) % N
        S[i], S[j] = S[j], S[i]
        keystream = S[(S[i] + S[j]) % N]
        out.extend(struct.pack('H', plaintext_shorts[x] ^ keystream))
    return bytes(out)

def bytes_to_shorts(data: bytes) -> list:
    """bytes → unsigned short 列表,不足補零"""
    if len(data) % 2:
        data += b'\x00'
    return list(struct.unpack(f'<{len(data)//2}H', data))

def shorts_to_bytes(shorts: list) -> bytes:
    return struct.pack(f'<{len(shorts)}H', *shorts)

def create_key(password: bytes) -> list:
    """從任意長度密碼衍生 32-byte 初始金鑰"""
    key = bytearray(32)
    plen = len(password)
    for i in range(32):
        key[i] = (password[i % plen] + i) % 256
    return list(key)

def update_key(key_shorts: list) -> list:
    """金鑰演進:循環左移 → 求和 → XOR → 再求和"""
    # short 列表 → bytes
    key_bytes = shorts_to_bytes(key_shorts)
    # 循環左移 1 byte
    key_bytes = key_bytes[1:] + key_bytes[:1]
    # 求和
    s = sum(key_bytes) % 256
    # XOR + 再求和
    new_bytes = bytearray()
    for b in key_bytes:
        nb = (b ^ s) % 256
        new_bytes.append(nb)
        s = (s + (nb >> 3)) % 256
    return bytes_to_shorts(new_bytes)

完整檔案加解密流程


def encrypt_file(in_path: str, out_path: str, password: str):
    key = create_key(password.encode())
    key_shorts = bytes_to_shorts(bytes(key))

    with open(in_path, 'rb') as fin, open(out_path, 'wb') as fout:
        # 寫入原始檔案長度 (4 bytes, little-endian)
        fin.seek(0, 2)
        file_len = fin.tell()
        fin.seek(0)
        fout.write(struct.pack('

使用範例


if __name__ == "__main__":
    import getpass
    src = input("來源檔案: ").strip()
    if not os.path.exists(src):
        sys.exit("檔案不存在")

    pwd = getpass.getpass("輸入密碼: ")
    if src.endswith(".rc4"):
        dst = src[:-4]
        decrypt_file(src, dst, pwd)
        print(f"解密完成 → {dst}")
    else:
        dst = src + ".rc4"
        encrypt_file(src, dst, pwd)
        print(f"加密完成 → {dst}")

安全性考量

  • **非標準 RC4**:擴充 S-Box 與金鑰演進屬自訂變體,未經學術密碼分析驗證,**嚴禁用於高機密資料**。
  • **無認證加密 (AEAD)**:僅有 CRC32 偵錯,無法防禦選擇密文攻擊 (CCA)。生產環境請改用 cryptography.fernet (AES-GCM) 或 NaCl/libsodium。
  • **金鑰衍生弱**:單純線性混合,建議前置 PBKDF2/Argon2/Scrypt。
  • **Python 2/3 相容**:本碼為 Python 3 專用 (bytes/str 分離),Python 2 需調整 struct.pack 格式字串與字串處理。
copyright © 萬盛學電腦網 all rights reserved