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 等查表數組 (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) |
window.crypto.subtle。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)) };
}