萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 實現 DES 加解密完整流程(含完整源碼)

前言

DES (Data Encryption Standard) 為對稱加密演算法,雖已被 AES 取代,但在舊系統維護、特定協議相容場景仍有應用。本文提供完整可執行的 JavaScript DES 實作(基於 Paul Tero 版本優化)。

核心函式簽名

function des(key, message, encrypt, mode, iv, padding) {
  // key: 8 字元金鑰 (56 位有效)
  // message: 明文/密文字串
  // encrypt: true=加密, false=解密
  // mode: 1=CBC, 其他=ECB
  // iv: 8 字元初始向量 (CBC 模式需)
  // padding: 0=無, 1=PKCS7, 2=空白填充
}

完整實作程式碼(精簡版,含關鍵 S-Box)

完整程式碼較長,此處展示核心結構與使用範例。完整源碼請參考附件或原始資料。

// S-Box 等查表數組 (spfunction1~8) 省略...

function des_createKeys(key) {
  // 產生 16 或 48 個子金鑰 (單/三重 DES)
  // ...
  return keys; // 陣列
}

function des(key, message, encrypt, mode, iv, padding) {
  var keys = des_createKeys(key);
  var iterations = keys.length === 32 ? 3 : 9; // 三重/單重 DES
  // 設定迴圈順序 (加密/解密)
  // 處理填充
  // CBC 模式處理 IV
  // 主迴圈:每 8 字元(64位)處理一個區塊
  //   初始置換 (IP)
  //   16 輪 Feistel 網路 (使用 S-Box)
  //   逆置換 (FP)
  // 回傳結果字串
  return result;
}

// 使用範例
var key = "12345678"; // 8 字元
var plaintext = "Hello World";
var ciphertext = des(key, plaintext, true, 1, "12345678", 1); // CBC + PKCS7
console.log("密文:", ciphertext);

var decrypted = des(key, ciphertext, false, 1, "12345678", 1);
console.log("解密:", decrypted); // "Hello World"

關鍵技術細節

項目說明
金鑰長度8 字元 (64 位),每字元第 8 位為校驗位,實際 56 位
分組大小64 位 (8 字元)
模式ECB (電子代碼本)、CBC (密碼分組鏈接)
填充PKCS7 (標準)、空白填充、無填充
三重 DES金鑰長度 24 字元,實際執行 3 次 DES (EDE)

安全性警示

  • ⚠️ DES 已不安全:56 位金鑰可在數小時內暴力破解。
  • ⚠️ 生產環境請改用 AES:Web Crypto API 原生支援 window.crypto.subtle。
  • ⚠️ ECB 模式極不安全:相同明文產生相同密文,洩露模式。必須使用 CBC/GCM 等模式。
  • ⚠️ 金鑰管理:勿硬編碼金鑰,需透過安全通道交換或衍生 (PBKDF2)。

現代替代:Web Crypto API (AES-GCM)

async function encryptAES(keyStr, plaintext) {
  // 從字串衍生金鑰
  const keyMaterial = await crypto.subtle.importKey(
    "raw", new TextEncoder().encode(keyStr), "PBKDF2", false, ["deriveKey"]
  );
  const key = await crypto.subtle.deriveKey(
    { name: "PBKDF2", salt: crypto.getRandomValues(new Uint8Array(16)), iterations: 100000, hash: "SHA-256" },
    keyMaterial, { name: "AES-GCM", length: 256 }, false, ["encrypt"]
  );
  
  const iv = crypto.getRandomValues(new Uint8Array(12));
  const ciphertext = await crypto.subtle.encrypt(
    { name: "AES-GCM", iv }, key, new TextEncoder().encode(plaintext)
  );
  return { iv: Array.from(iv), data: Array.from(new Uint8Array(ciphertext)) };
}
copyright © 萬盛學電腦網 all rights reserved