From fa219d96f16358bfe64721f4be0885adb51c4800 Mon Sep 17 00:00:00 2001 From: Thomas M <44269971+thomasxm@users.noreply.github.com> Date: Sun, 5 Jul 2026 11:11:31 +0100 Subject: [PATCH 1/2] feat: add PRESENT and Twofish ciphers (#2157) --- src/core/config/Categories.json | 4 + src/core/lib/Present.mjs | 422 +++++++++++++++++ src/core/lib/Twofish.mjs | 608 +++++++++++++++++++++++++ src/core/operations/PRESENTDecrypt.mjs | 94 ++++ src/core/operations/PRESENTEncrypt.mjs | 94 ++++ src/core/operations/TwofishDecrypt.mjs | 94 ++++ src/core/operations/TwofishEncrypt.mjs | 94 ++++ tests/operations/tests/PRESENT.mjs | 465 +++++++++++++++++++ tests/operations/tests/Twofish.mjs | 486 ++++++++++++++++++++ 9 files changed, 2361 insertions(+) create mode 100644 src/core/lib/Present.mjs create mode 100644 src/core/lib/Twofish.mjs create mode 100644 src/core/operations/PRESENTDecrypt.mjs create mode 100644 src/core/operations/PRESENTEncrypt.mjs create mode 100644 src/core/operations/TwofishDecrypt.mjs create mode 100644 src/core/operations/TwofishEncrypt.mjs create mode 100644 tests/operations/tests/PRESENT.mjs create mode 100644 tests/operations/tests/Twofish.mjs diff --git a/src/core/config/Categories.json b/src/core/config/Categories.json index a417af775e..8c64c398d5 100644 --- a/src/core/config/Categories.json +++ b/src/core/config/Categories.json @@ -115,6 +115,10 @@ "RC6 Decrypt", "Ascon Encrypt", "Ascon Decrypt", + "PRESENT Encrypt", + "PRESENT Decrypt", + "Twofish Encrypt", + "Twofish Decrypt", "GOST Encrypt", "GOST Decrypt", "GOST Sign", diff --git a/src/core/lib/Present.mjs b/src/core/lib/Present.mjs new file mode 100644 index 0000000000..ffb6bf57aa --- /dev/null +++ b/src/core/lib/Present.mjs @@ -0,0 +1,422 @@ +/** + * Complete implementation of PRESENT block cipher encryption/decryption with + * ECB and CBC block modes. + * + * PRESENT is an ultra-lightweight block cipher designed for constrained environments. + * Standardised in ISO/IEC 29192-2:2019. + * + * Reference: "PRESENT: An Ultra-Lightweight Block Cipher" + * https://link.springer.com/chapter/10.1007/978-3-540-74735-2_31 + * + * @author Medjedtxm + * @copyright Crown Copyright 2026 + * @license Apache-2.0 + */ + +import OperationError from "../errors/OperationError.mjs"; + +/** Number of rounds */ +const NROUNDS = 31; + +/** Block size in bytes (64 bits) */ +const BLOCKSIZE = 8; + +/** The 4-bit S-box (16 values) */ +const SBOX = [ + 0xC, 0x5, 0x6, 0xB, 0x9, 0x0, 0xA, 0xD, + 0x3, 0xE, 0xF, 0x8, 0x4, 0x7, 0x1, 0x2 +]; + +/** Inverse S-box for decryption */ +const SBOX_INV = [ + 0x5, 0xE, 0xF, 0x8, 0xC, 0x1, 0x2, 0xD, + 0xB, 0x4, 0x6, 0x3, 0x0, 0x7, 0x9, 0xA +]; + +/** P-layer permutation table (bit i goes to position P[i]) */ +const PBOX = [ + 0, 16, 32, 48, 1, 17, 33, 49, 2, 18, 34, 50, 3, 19, 35, 51, + 4, 20, 36, 52, 5, 21, 37, 53, 6, 22, 38, 54, 7, 23, 39, 55, + 8, 24, 40, 56, 9, 25, 41, 57, 10, 26, 42, 58, 11, 27, 43, 59, + 12, 28, 44, 60, 13, 29, 45, 61, 14, 30, 46, 62, 15, 31, 47, 63 +]; + +/** Inverse P-layer permutation for decryption */ +const PBOX_INV = new Array(64); +for (let i = 0; i < 64; i++) { + PBOX_INV[PBOX[i]] = i; +} + +/** + * Convert byte array to BigInt (big-endian) + * @param {number[]} bytes - Array of bytes + * @returns {bigint} - 64-bit value as BigInt + */ +function bytesToBigInt(bytes) { + let result = 0n; + for (let i = 0; i < bytes.length; i++) { + result = (result << 8n) | BigInt(bytes[i]); + } + return result; +} + +/** + * Convert BigInt to byte array (big-endian) + * @param {bigint} value - BigInt value + * @param {number} length - Desired byte array length + * @returns {number[]} - Array of bytes + */ +function bigIntToBytes(value, length) { + const bytes = []; + for (let i = length - 1; i >= 0; i--) { + bytes[i] = Number(value & 0xFFn); + value >>= 8n; + } + return bytes; +} + +/** + * Apply S-box substitution layer to 64-bit state + * @param {bigint} state - 64-bit state + * @param {number[]} sbox - S-box to use + * @returns {bigint} - Substituted state + */ +function sBoxLayer(state, sbox) { + let result = 0n; + for (let i = 0; i < 16; i++) { + const nibble = Number((state >> BigInt(i * 4)) & 0xFn); + result |= BigInt(sbox[nibble]) << BigInt(i * 4); + } + return result; +} + +/** + * Apply P-layer permutation to 64-bit state + * @param {bigint} state - 64-bit state + * @param {number[]} pbox - Permutation table to use + * @returns {bigint} - Permuted state + */ +function pLayer(state, pbox) { + let result = 0n; + for (let i = 0; i < 64; i++) { + if ((state >> BigInt(i)) & 1n) { + result |= 1n << BigInt(pbox[i]); + } + } + return result; +} + +/** + * Generate round keys for 80-bit key + * @param {number[]} key - 10-byte key + * @returns {bigint[]} - Array of 32 round keys (64-bit each) + */ +function generateRoundKeys80(key) { + // Key register is 80 bits + let keyReg = bytesToBigInt(key); + const roundKeys = []; + + for (let i = 1; i <= NROUNDS + 1; i++) { + // Extract round key (leftmost 64 bits) + roundKeys.push(keyReg >> 16n); + + // Rotate left by 61 positions + keyReg = ((keyReg << 61n) | (keyReg >> 19n)) & ((1n << 80n) - 1n); + + // Apply S-box to leftmost 4 bits + const leftNibble = Number(keyReg >> 76n); + keyReg = (keyReg & ((1n << 76n) - 1n)) | (BigInt(SBOX[leftNibble]) << 76n); + + // XOR round counter to bits 19-15 + keyReg ^= BigInt(i) << 15n; + } + + return roundKeys; +} + +/** + * Generate round keys for 128-bit key + * @param {number[]} key - 16-byte key + * @returns {bigint[]} - Array of 32 round keys (64-bit each) + */ +function generateRoundKeys128(key) { + // Key register is 128 bits + let keyReg = bytesToBigInt(key); + const roundKeys = []; + + for (let i = 1; i <= NROUNDS + 1; i++) { + // Extract round key (leftmost 64 bits) + roundKeys.push(keyReg >> 64n); + + // Rotate left by 61 positions + keyReg = ((keyReg << 61n) | (keyReg >> 67n)) & ((1n << 128n) - 1n); + + // Apply S-box to leftmost 8 bits (two nibbles: bits 127-124 and 123-120) + const leftByte = Number((keyReg >> 120n) & 0xFFn); + const leftNibble1 = (leftByte >> 4) & 0xF; // bits 127-124 + const leftNibble2 = leftByte & 0xF; // bits 123-120 + keyReg = (keyReg & ((1n << 120n) - 1n)) | + (BigInt((SBOX[leftNibble1] << 4) | SBOX[leftNibble2]) << 120n); + + // XOR round counter to bits 66-62 + keyReg ^= BigInt(i) << 62n; + } + + return roundKeys; +} + +/** + * Encrypt a single 64-bit block + * @param {bigint} block - 64-bit plaintext block + * @param {bigint[]} roundKeys - Round keys + * @returns {bigint} - 64-bit ciphertext block + */ +function encryptBlock(block, roundKeys) { + let state = block; + + for (let i = 0; i < NROUNDS; i++) { + // Add round key + state ^= roundKeys[i]; + // S-box layer + state = sBoxLayer(state, SBOX); + // P-layer + state = pLayer(state, PBOX); + } + + // Final round key addition + state ^= roundKeys[NROUNDS]; + + return state; +} + +/** + * Decrypt a single 64-bit block + * @param {bigint} block - 64-bit ciphertext block + * @param {bigint[]} roundKeys - Round keys + * @returns {bigint} - 64-bit plaintext block + */ +function decryptBlock(block, roundKeys) { + let state = block; + + // Reverse key addition + state ^= roundKeys[NROUNDS]; + + for (let i = NROUNDS - 1; i >= 0; i--) { + // Inverse P-layer + state = pLayer(state, PBOX_INV); + // Inverse S-box layer + state = sBoxLayer(state, SBOX_INV); + // Add round key + state ^= roundKeys[i]; + } + + return state; +} + +/** + * Apply padding to message + * @param {number[]} message - Original message + * @param {string} padding - Padding type ("NO", "PKCS5", "ZERO", "RANDOM", "BIT") + * @param {number} blockSize - Block size in bytes + * @returns {number[]} - Padded message + */ +function applyPadding(message, padding, blockSize) { + const remainder = message.length % blockSize; + let nPadding = remainder === 0 ? 0 : blockSize - remainder; + + // For PKCS5, always add at least one byte (full block if already aligned) + if (padding === "PKCS5" && remainder === 0) { + nPadding = blockSize; + } + + if (nPadding === 0) return [...message]; + + const paddedMessage = [...message]; + + switch (padding) { + case "NO": + throw new OperationError(`No padding requested but input is not a ${blockSize}-byte multiple.`); + + case "PKCS5": + for (let i = 0; i < nPadding; i++) { + paddedMessage.push(nPadding); + } + break; + + case "ZERO": + for (let i = 0; i < nPadding; i++) { + paddedMessage.push(0); + } + break; + + case "RANDOM": + for (let i = 0; i < nPadding; i++) { + paddedMessage.push(Math.floor(Math.random() * 256)); + } + break; + + case "BIT": + paddedMessage.push(0x80); + for (let i = 1; i < nPadding; i++) { + paddedMessage.push(0); + } + break; + + default: + throw new OperationError(`Unknown padding type: ${padding}`); + } + + return paddedMessage; +} + +/** + * Remove padding from message + * @param {number[]} message - Padded message + * @param {string} padding - Padding type ("NO", "PKCS5", "ZERO", "RANDOM", "BIT") + * @param {number} blockSize - Block size in bytes + * @returns {number[]} - Unpadded message + */ +function removePadding(message, padding, blockSize) { + if (message.length === 0) return message; + + switch (padding) { + case "NO": + case "ZERO": + case "RANDOM": + // These padding types cannot be reliably removed + return message; + + case "PKCS5": { + const padByte = message[message.length - 1]; + if (padByte > 0 && padByte <= blockSize) { + // Verify padding + for (let i = 0; i < padByte; i++) { + if (message[message.length - 1 - i] !== padByte) { + throw new OperationError("Invalid PKCS#5 padding."); + } + } + return message.slice(0, message.length - padByte); + } + throw new OperationError("Invalid PKCS#5 padding."); + } + + case "BIT": { + // Find 0x80 byte working backwards, skipping zeros + for (let i = message.length - 1; i >= 0; i--) { + if (message[i] === 0x80) { + return message.slice(0, i); + } else if (message[i] !== 0) { + throw new OperationError("Invalid BIT padding."); + } + } + throw new OperationError("Invalid BIT padding."); + } + + default: + throw new OperationError(`Unknown padding type: ${padding}`); + } +} + +/** + * Encrypt using PRESENT cipher with specified block mode + * + * @param {number[]} message - Plaintext as byte array + * @param {number[]} key - Key (10 bytes for 80-bit or 16 bytes for 128-bit) + * @param {number[]} iv - IV (8 bytes, not used for ECB) + * @param {string} mode - Block cipher mode ("ECB" or "CBC") + * @param {string} padding - Padding type ("NO", "PKCS5", "ZERO", "RANDOM", "BIT") + * @returns {number[]} - Ciphertext as byte array + */ +export function encryptPRESENT(message, key, iv, mode = "ECB", padding = "PKCS5") { + if (message.length === 0) return []; + + // Generate round keys based on key length + const roundKeys = key.length === 10 ? + generateRoundKeys80(key) : + generateRoundKeys128(key); + + // Apply padding + const paddedMessage = applyPadding(message, padding, BLOCKSIZE); + + const cipherText = []; + + switch (mode) { + case "ECB": + for (let i = 0; i < paddedMessage.length; i += BLOCKSIZE) { + const block = bytesToBigInt(paddedMessage.slice(i, i + BLOCKSIZE)); + const encrypted = encryptBlock(block, roundKeys); + cipherText.push(...bigIntToBytes(encrypted, BLOCKSIZE)); + } + break; + + case "CBC": { + let ivBlock = bytesToBigInt(iv); + for (let i = 0; i < paddedMessage.length; i += BLOCKSIZE) { + let block = bytesToBigInt(paddedMessage.slice(i, i + BLOCKSIZE)); + block ^= ivBlock; + const encrypted = encryptBlock(block, roundKeys); + cipherText.push(...bigIntToBytes(encrypted, BLOCKSIZE)); + ivBlock = encrypted; + } + break; + } + + default: + throw new OperationError(`Invalid block cipher mode: ${mode}`); + } + + return cipherText; +} + +/** + * Decrypt using PRESENT cipher with specified block mode + * + * @param {number[]} cipherText - Ciphertext as byte array + * @param {number[]} key - Key (10 bytes for 80-bit or 16 bytes for 128-bit) + * @param {number[]} iv - IV (8 bytes, not used for ECB) + * @param {string} mode - Block cipher mode ("ECB" or "CBC") + * @param {string} padding - Padding type ("NO", "PKCS5", "ZERO", "RANDOM", "BIT") + * @returns {number[]} - Plaintext as byte array + */ +export function decryptPRESENT(cipherText, key, iv, mode = "ECB", padding = "PKCS5") { + if (cipherText.length === 0) return []; + + if (cipherText.length % BLOCKSIZE !== 0) { + throw new OperationError(`Invalid ciphertext length: ${cipherText.length} bytes. Must be a multiple of 8.`); + } + + // Generate round keys based on key length + const roundKeys = key.length === 10 ? + generateRoundKeys80(key) : + generateRoundKeys128(key); + + const plainText = []; + + switch (mode) { + case "ECB": + for (let i = 0; i < cipherText.length; i += BLOCKSIZE) { + const block = bytesToBigInt(cipherText.slice(i, i + BLOCKSIZE)); + const decrypted = decryptBlock(block, roundKeys); + plainText.push(...bigIntToBytes(decrypted, BLOCKSIZE)); + } + break; + + case "CBC": { + let ivBlock = bytesToBigInt(iv); + for (let i = 0; i < cipherText.length; i += BLOCKSIZE) { + const block = bytesToBigInt(cipherText.slice(i, i + BLOCKSIZE)); + let decrypted = decryptBlock(block, roundKeys); + decrypted ^= ivBlock; + plainText.push(...bigIntToBytes(decrypted, BLOCKSIZE)); + ivBlock = block; + } + break; + } + + default: + throw new OperationError(`Invalid block cipher mode: ${mode}`); + } + + // Remove padding + return removePadding(plainText, padding, BLOCKSIZE); +} diff --git a/src/core/lib/Twofish.mjs b/src/core/lib/Twofish.mjs new file mode 100644 index 0000000000..2654df4097 --- /dev/null +++ b/src/core/lib/Twofish.mjs @@ -0,0 +1,608 @@ +/** + * Complete implementation of Twofish block cipher encryption/decryption with + * ECB, CBC, CFB, OFB, CTR block modes. + * + * Twofish was an AES finalist designed by Bruce Schneier et al. + * Reference: https://www.schneier.com/academic/twofish/ + * + * @author Medjedtxm + * @copyright Crown Copyright 2026 + * @license Apache-2.0 + */ + +import OperationError from "../errors/OperationError.mjs"; + +/** Number of rounds */ +const NROUNDS = 16; + +/** Block size in bytes (128 bits) */ +const BLOCKSIZE = 16; + +/** Q0 permutation */ +const Q0 = [ + 0xa9, 0x67, 0xb3, 0xe8, 0x04, 0xfd, 0xa3, 0x76, 0x9a, 0x92, 0x80, 0x78, 0xe4, 0xdd, 0xd1, 0x38, + 0x0d, 0xc6, 0x35, 0x98, 0x18, 0xf7, 0xec, 0x6c, 0x43, 0x75, 0x37, 0x26, 0xfa, 0x13, 0x94, 0x48, + 0xf2, 0xd0, 0x8b, 0x30, 0x84, 0x54, 0xdf, 0x23, 0x19, 0x5b, 0x3d, 0x59, 0xf3, 0xae, 0xa2, 0x82, + 0x63, 0x01, 0x83, 0x2e, 0xd9, 0x51, 0x9b, 0x7c, 0xa6, 0xeb, 0xa5, 0xbe, 0x16, 0x0c, 0xe3, 0x61, + 0xc0, 0x8c, 0x3a, 0xf5, 0x73, 0x2c, 0x25, 0x0b, 0xbb, 0x4e, 0x89, 0x6b, 0x53, 0x6a, 0xb4, 0xf1, + 0xe1, 0xe6, 0xbd, 0x45, 0xe2, 0xf4, 0xb6, 0x66, 0xcc, 0x95, 0x03, 0x56, 0xd4, 0x1c, 0x1e, 0xd7, + 0xfb, 0xc3, 0x8e, 0xb5, 0xe9, 0xcf, 0xbf, 0xba, 0xea, 0x77, 0x39, 0xaf, 0x33, 0xc9, 0x62, 0x71, + 0x81, 0x79, 0x09, 0xad, 0x24, 0xcd, 0xf9, 0xd8, 0xe5, 0xc5, 0xb9, 0x4d, 0x44, 0x08, 0x86, 0xe7, + 0xa1, 0x1d, 0xaa, 0xed, 0x06, 0x70, 0xb2, 0xd2, 0x41, 0x7b, 0xa0, 0x11, 0x31, 0xc2, 0x27, 0x90, + 0x20, 0xf6, 0x60, 0xff, 0x96, 0x5c, 0xb1, 0xab, 0x9e, 0x9c, 0x52, 0x1b, 0x5f, 0x93, 0x0a, 0xef, + 0x91, 0x85, 0x49, 0xee, 0x2d, 0x4f, 0x8f, 0x3b, 0x47, 0x87, 0x6d, 0x46, 0xd6, 0x3e, 0x69, 0x64, + 0x2a, 0xce, 0xcb, 0x2f, 0xfc, 0x97, 0x05, 0x7a, 0xac, 0x7f, 0xd5, 0x1a, 0x4b, 0x0e, 0xa7, 0x5a, + 0x28, 0x14, 0x3f, 0x29, 0x88, 0x3c, 0x4c, 0x02, 0xb8, 0xda, 0xb0, 0x17, 0x55, 0x1f, 0x8a, 0x7d, + 0x57, 0xc7, 0x8d, 0x74, 0xb7, 0xc4, 0x9f, 0x72, 0x7e, 0x15, 0x22, 0x12, 0x58, 0x07, 0x99, 0x34, + 0x6e, 0x50, 0xde, 0x68, 0x65, 0xbc, 0xdb, 0xf8, 0xc8, 0xa8, 0x2b, 0x40, 0xdc, 0xfe, 0x32, 0xa4, + 0xca, 0x10, 0x21, 0xf0, 0xd3, 0x5d, 0x0f, 0x00, 0x6f, 0x9d, 0x36, 0x42, 0x4a, 0x5e, 0xc1, 0xe0 +]; + +/** Q1 permutation */ +const Q1 = [ + 0x75, 0xf3, 0xc6, 0xf4, 0xdb, 0x7b, 0xfb, 0xc8, 0x4a, 0xd3, 0xe6, 0x6b, 0x45, 0x7d, 0xe8, 0x4b, + 0xd6, 0x32, 0xd8, 0xfd, 0x37, 0x71, 0xf1, 0xe1, 0x30, 0x0f, 0xf8, 0x1b, 0x87, 0xfa, 0x06, 0x3f, + 0x5e, 0xba, 0xae, 0x5b, 0x8a, 0x00, 0xbc, 0x9d, 0x6d, 0xc1, 0xb1, 0x0e, 0x80, 0x5d, 0xd2, 0xd5, + 0xa0, 0x84, 0x07, 0x14, 0xb5, 0x90, 0x2c, 0xa3, 0xb2, 0x73, 0x4c, 0x54, 0x92, 0x74, 0x36, 0x51, + 0x38, 0xb0, 0xbd, 0x5a, 0xfc, 0x60, 0x62, 0x96, 0x6c, 0x42, 0xf7, 0x10, 0x7c, 0x28, 0x27, 0x8c, + 0x13, 0x95, 0x9c, 0xc7, 0x24, 0x46, 0x3b, 0x70, 0xca, 0xe3, 0x85, 0xcb, 0x11, 0xd0, 0x93, 0xb8, + 0xa6, 0x83, 0x20, 0xff, 0x9f, 0x77, 0xc3, 0xcc, 0x03, 0x6f, 0x08, 0xbf, 0x40, 0xe7, 0x2b, 0xe2, + 0x79, 0x0c, 0xaa, 0x82, 0x41, 0x3a, 0xea, 0xb9, 0xe4, 0x9a, 0xa4, 0x97, 0x7e, 0xda, 0x7a, 0x17, + 0x66, 0x94, 0xa1, 0x1d, 0x3d, 0xf0, 0xde, 0xb3, 0x0b, 0x72, 0xa7, 0x1c, 0xef, 0xd1, 0x53, 0x3e, + 0x8f, 0x33, 0x26, 0x5f, 0xec, 0x76, 0x2a, 0x49, 0x81, 0x88, 0xee, 0x21, 0xc4, 0x1a, 0xeb, 0xd9, + 0xc5, 0x39, 0x99, 0xcd, 0xad, 0x31, 0x8b, 0x01, 0x18, 0x23, 0xdd, 0x1f, 0x4e, 0x2d, 0xf9, 0x48, + 0x4f, 0xf2, 0x65, 0x8e, 0x78, 0x5c, 0x58, 0x19, 0x8d, 0xe5, 0x98, 0x57, 0x67, 0x7f, 0x05, 0x64, + 0xaf, 0x63, 0xb6, 0xfe, 0xf5, 0xb7, 0x3c, 0xa5, 0xce, 0xe9, 0x68, 0x44, 0xe0, 0x4d, 0x43, 0x69, + 0x29, 0x2e, 0xac, 0x15, 0x59, 0xa8, 0x0a, 0x9e, 0x6e, 0x47, 0xdf, 0x34, 0x35, 0x6a, 0xcf, 0xdc, + 0x22, 0xc9, 0xc0, 0x9b, 0x89, 0xd4, 0xed, 0xab, 0x12, 0xa2, 0x0d, 0x52, 0xbb, 0x02, 0x2f, 0xa9, + 0xd7, 0x61, 0x1e, 0xb4, 0x50, 0x04, 0xf6, 0xc2, 0x16, 0x25, 0x86, 0x56, 0x55, 0x09, 0xbe, 0x91 +]; + +/** Reed-Solomon matrix for key schedule */ +const RS = [ + [0x01, 0xA4, 0x55, 0x87, 0x5A, 0x58, 0xDB, 0x9E], + [0xA4, 0x56, 0x82, 0xF3, 0x1E, 0xC6, 0x68, 0xE5], + [0x02, 0xA1, 0xFC, 0xC1, 0x47, 0xAE, 0x3D, 0x19], + [0xA4, 0x55, 0x87, 0x5A, 0x58, 0xDB, 0x9E, 0x03] +]; + +/** + * Galois Field multiplication in GF(2^8) with polynomial 0x169 + */ +function gfMult(a, b, poly) { + let result = 0; + while (b) { + if (b & 1) result ^= a; + a <<= 1; + if (a & 0x100) a ^= poly; + b >>>= 1; + } + return result & 0xFF; +} + +/** + * MDS multiplication + */ +function mdsMultiply(x) { + const b0 = x & 0xFF; + const b1 = (x >>> 8) & 0xFF; + const b2 = (x >>> 16) & 0xFF; + const b3 = (x >>> 24) & 0xFF; + + // MDS matrix multiplication in GF(2^8) with polynomial 0x169 + const r0 = gfMult(b0, 0x01, 0x169) ^ gfMult(b1, 0xEF, 0x169) ^ gfMult(b2, 0x5B, 0x169) ^ gfMult(b3, 0x5B, 0x169); + const r1 = gfMult(b0, 0x5B, 0x169) ^ gfMult(b1, 0xEF, 0x169) ^ gfMult(b2, 0xEF, 0x169) ^ gfMult(b3, 0x01, 0x169); + const r2 = gfMult(b0, 0xEF, 0x169) ^ gfMult(b1, 0x5B, 0x169) ^ gfMult(b2, 0x01, 0x169) ^ gfMult(b3, 0xEF, 0x169); + const r3 = gfMult(b0, 0xEF, 0x169) ^ gfMult(b1, 0x01, 0x169) ^ gfMult(b2, 0xEF, 0x169) ^ gfMult(b3, 0x5B, 0x169); + + return (r3 << 24) | (r2 << 16) | (r1 << 8) | r0; +} + +/** + * Reed-Solomon multiplication for key schedule + */ +function rsMultiply(key8) { + let result = 0; + for (let i = 0; i < 4; i++) { + let x = 0; + for (let j = 0; j < 8; j++) { + x ^= gfMult(RS[i][j], key8[j], 0x14D); + } + result |= x << (i * 8); + } + return result; +} + +/** + * Apply h function (the main keyed permutation) + */ +function h(x, L, k) { + const y = new Array(4); + y[0] = x & 0xFF; + y[1] = (x >>> 8) & 0xFF; + y[2] = (x >>> 16) & 0xFF; + y[3] = (x >>> 24) & 0xFF; + + if (k === 4) { + y[0] = Q1[y[0]] ^ (L[3] & 0xFF); + y[1] = Q0[y[1]] ^ ((L[3] >>> 8) & 0xFF); + y[2] = Q0[y[2]] ^ ((L[3] >>> 16) & 0xFF); + y[3] = Q1[y[3]] ^ ((L[3] >>> 24) & 0xFF); + } + if (k >= 3) { + y[0] = Q1[y[0]] ^ (L[2] & 0xFF); + y[1] = Q1[y[1]] ^ ((L[2] >>> 8) & 0xFF); + y[2] = Q0[y[2]] ^ ((L[2] >>> 16) & 0xFF); + y[3] = Q0[y[3]] ^ ((L[2] >>> 24) & 0xFF); + } + + // Always do k >= 2 + y[0] = Q0[Q0[y[0]] ^ (L[1] & 0xFF)] ^ (L[0] & 0xFF); + y[1] = Q0[Q1[y[1]] ^ ((L[1] >>> 8) & 0xFF)] ^ ((L[0] >>> 8) & 0xFF); + y[2] = Q1[Q0[y[2]] ^ ((L[1] >>> 16) & 0xFF)] ^ ((L[0] >>> 16) & 0xFF); + y[3] = Q1[Q1[y[3]] ^ ((L[1] >>> 24) & 0xFF)] ^ ((L[0] >>> 24) & 0xFF); + + // Final q-box lookup + y[0] = Q1[y[0]]; + y[1] = Q0[y[1]]; + y[2] = Q1[y[2]]; + y[3] = Q0[y[3]]; + + return mdsMultiply((y[3] << 24) | (y[2] << 16) | (y[1] << 8) | y[0]); +} + +/** + * Rotate left 32-bit + */ +function ROL(x, n) { + return ((x << n) | (x >>> (32 - n))) >>> 0; +} + +/** + * Rotate right 32-bit + */ +function ROR(x, n) { + return ((x >>> n) | (x << (32 - n))) >>> 0; +} + +/** + * Generate subkeys from the key + */ +function generateSubkeys(key) { + const keyLen = key.length; + const k = keyLen / 8; // 2, 3, or 4 + + // Split key into Me (even words) and Mo (odd words) + const Me = new Array(k); + const Mo = new Array(k); + + for (let i = 0; i < k; i++) { + const offset = i * 8; + Me[i] = (key[offset]) | (key[offset + 1] << 8) | + (key[offset + 2] << 16) | (key[offset + 3] << 24); + Mo[i] = (key[offset + 4]) | (key[offset + 5] << 8) | + (key[offset + 6] << 16) | (key[offset + 7] << 24); + } + + // Generate S-box keys using Reed-Solomon + const S = new Array(k); + for (let i = 0; i < k; i++) { + const offset = (k - 1 - i) * 8; + S[i] = rsMultiply(key.slice(offset, offset + 8)); + } + + // Generate round subkeys + const subkeys = new Array(40); + const rho = 0x01010101; + + for (let i = 0; i < 20; i++) { + const A = h(2 * i * rho, Me, k); + const B = ROL(h((2 * i + 1) * rho, Mo, k), 8); + subkeys[2 * i] = (A + B) >>> 0; + subkeys[2 * i + 1] = ROL((A + 2 * B) >>> 0, 9); + } + + return { subkeys, S, k }; +} + +/** + * g function using precomputed S-box keys + */ +function g(x, S, k) { + return h(x, S, k); +} + +/** + * Encrypt a single 128-bit block + */ +function encryptBlock(block, keyData) { + const { subkeys, S, k } = keyData; + + // Split block into 4 words (little-endian) + let R0 = (block[0]) | (block[1] << 8) | (block[2] << 16) | (block[3] << 24); + let R1 = (block[4]) | (block[5] << 8) | (block[6] << 16) | (block[7] << 24); + let R2 = (block[8]) | (block[9] << 8) | (block[10] << 16) | (block[11] << 24); + let R3 = (block[12]) | (block[13] << 8) | (block[14] << 16) | (block[15] << 24); + + // Input whitening + R0 ^= subkeys[0]; + R1 ^= subkeys[1]; + R2 ^= subkeys[2]; + R3 ^= subkeys[3]; + + // 16 rounds + for (let r = 0; r < NROUNDS; r += 2) { + let T0 = g(R0, S, k); + let T1 = g(ROL(R1, 8), S, k); + R2 = ROR(R2 ^ ((T0 + T1 + subkeys[8 + 2 * r]) >>> 0), 1); + R3 = ROL(R3, 1) ^ ((T0 + 2 * T1 + subkeys[9 + 2 * r]) >>> 0); + + T0 = g(R2, S, k); + T1 = g(ROL(R3, 8), S, k); + R0 = ROR(R0 ^ ((T0 + T1 + subkeys[8 + 2 * r + 2]) >>> 0), 1); + R1 = ROL(R1, 1) ^ ((T0 + 2 * T1 + subkeys[9 + 2 * r + 2]) >>> 0); + } + + // Output whitening (with undo of last swap) + R2 ^= subkeys[4]; + R3 ^= subkeys[5]; + R0 ^= subkeys[6]; + R1 ^= subkeys[7]; + + // Convert back to bytes (little-endian) + return [ + R2 & 0xFF, (R2 >>> 8) & 0xFF, (R2 >>> 16) & 0xFF, (R2 >>> 24) & 0xFF, + R3 & 0xFF, (R3 >>> 8) & 0xFF, (R3 >>> 16) & 0xFF, (R3 >>> 24) & 0xFF, + R0 & 0xFF, (R0 >>> 8) & 0xFF, (R0 >>> 16) & 0xFF, (R0 >>> 24) & 0xFF, + R1 & 0xFF, (R1 >>> 8) & 0xFF, (R1 >>> 16) & 0xFF, (R1 >>> 24) & 0xFF + ]; +} + +/** + * Decrypt a single 128-bit block + */ +function decryptBlock(block, keyData) { + const { subkeys, S, k } = keyData; + + // Split block into 4 words (little-endian) + let R0 = (block[0]) | (block[1] << 8) | (block[2] << 16) | (block[3] << 24); + let R1 = (block[4]) | (block[5] << 8) | (block[6] << 16) | (block[7] << 24); + let R2 = (block[8]) | (block[9] << 8) | (block[10] << 16) | (block[11] << 24); + let R3 = (block[12]) | (block[13] << 8) | (block[14] << 16) | (block[15] << 24); + + // Input whitening (reverse of output whitening) + R0 ^= subkeys[4]; + R1 ^= subkeys[5]; + R2 ^= subkeys[6]; + R3 ^= subkeys[7]; + + // 16 rounds in reverse + for (let r = NROUNDS - 2; r >= 0; r -= 2) { + let T0 = g(R0, S, k); + let T1 = g(ROL(R1, 8), S, k); + R2 = ROL(R2, 1) ^ ((T0 + T1 + subkeys[8 + 2 * r + 2]) >>> 0); + R3 = ROR(R3 ^ ((T0 + 2 * T1 + subkeys[9 + 2 * r + 2]) >>> 0), 1); + + T0 = g(R2, S, k); + T1 = g(ROL(R3, 8), S, k); + R0 = ROL(R0, 1) ^ ((T0 + T1 + subkeys[8 + 2 * r]) >>> 0); + R1 = ROR(R1 ^ ((T0 + 2 * T1 + subkeys[9 + 2 * r]) >>> 0), 1); + } + + // Output whitening (reverse of input whitening) + R2 ^= subkeys[0]; + R3 ^= subkeys[1]; + R0 ^= subkeys[2]; + R1 ^= subkeys[3]; + + // Convert back to bytes (little-endian) + return [ + R2 & 0xFF, (R2 >>> 8) & 0xFF, (R2 >>> 16) & 0xFF, (R2 >>> 24) & 0xFF, + R3 & 0xFF, (R3 >>> 8) & 0xFF, (R3 >>> 16) & 0xFF, (R3 >>> 24) & 0xFF, + R0 & 0xFF, (R0 >>> 8) & 0xFF, (R0 >>> 16) & 0xFF, (R0 >>> 24) & 0xFF, + R1 & 0xFF, (R1 >>> 8) & 0xFF, (R1 >>> 16) & 0xFF, (R1 >>> 24) & 0xFF + ]; +} + +/** + * XOR two 16-byte blocks + */ +function xorBlocks(a, b) { + const result = new Array(16); + for (let i = 0; i < 16; i++) { + result[i] = a[i] ^ b[i]; + } + return result; +} + +/** + * Increment counter (little-endian) + */ +function incrementCounter(counter) { + const result = [...counter]; + for (let i = 0; i < 16; i++) { + result[i]++; + if (result[i] <= 255) break; + result[i] = 0; + } + return result; +} + +/** + * Apply padding to message + * @param {number[]} message - Original message + * @param {string} padding - Padding type ("NO", "PKCS5", "ZERO", "RANDOM", "BIT") + * @param {number} blockSize - Block size in bytes + * @returns {number[]} - Padded message + */ +function applyPadding(message, padding, blockSize) { + const remainder = message.length % blockSize; + let nPadding = remainder === 0 ? 0 : blockSize - remainder; + + // For PKCS5, always add at least one byte (full block if already aligned) + if (padding === "PKCS5" && remainder === 0) { + nPadding = blockSize; + } + + if (nPadding === 0) return [...message]; + + const paddedMessage = [...message]; + + switch (padding) { + case "NO": + throw new OperationError(`No padding requested but input is not a ${blockSize}-byte multiple.`); + + case "PKCS5": + for (let i = 0; i < nPadding; i++) { + paddedMessage.push(nPadding); + } + break; + + case "ZERO": + for (let i = 0; i < nPadding; i++) { + paddedMessage.push(0); + } + break; + + case "RANDOM": + for (let i = 0; i < nPadding; i++) { + paddedMessage.push(Math.floor(Math.random() * 256)); + } + break; + + case "BIT": + paddedMessage.push(0x80); + for (let i = 1; i < nPadding; i++) { + paddedMessage.push(0); + } + break; + + default: + throw new OperationError(`Unknown padding type: ${padding}`); + } + + return paddedMessage; +} + +/** + * Remove padding from message + * @param {number[]} message - Padded message + * @param {string} padding - Padding type ("NO", "PKCS5", "ZERO", "RANDOM", "BIT") + * @param {number} blockSize - Block size in bytes + * @returns {number[]} - Unpadded message + */ +function removePadding(message, padding, blockSize) { + if (message.length === 0) return message; + + switch (padding) { + case "NO": + case "ZERO": + case "RANDOM": + // These padding types cannot be reliably removed + return message; + + case "PKCS5": { + const padByte = message[message.length - 1]; + if (padByte > 0 && padByte <= blockSize) { + // Verify padding + for (let i = 0; i < padByte; i++) { + if (message[message.length - 1 - i] !== padByte) { + throw new OperationError("Invalid PKCS#5 padding."); + } + } + return message.slice(0, message.length - padByte); + } + throw new OperationError("Invalid PKCS#5 padding."); + } + + case "BIT": { + // Find 0x80 byte working backwards, skipping zeros + for (let i = message.length - 1; i >= 0; i--) { + if (message[i] === 0x80) { + return message.slice(0, i); + } else if (message[i] !== 0) { + throw new OperationError("Invalid BIT padding."); + } + } + throw new OperationError("Invalid BIT padding."); + } + + default: + throw new OperationError(`Unknown padding type: ${padding}`); + } +} + +/** + * Encrypt using Twofish cipher with specified block mode + * + * @param {number[]} message - Plaintext as byte array + * @param {number[]} key - Key (16, 24, or 32 bytes) + * @param {number[]} iv - IV (16 bytes, not used for ECB) + * @param {string} mode - Block cipher mode ("ECB", "CBC", "CFB", "OFB", "CTR") + * @param {string} padding - Padding type ("NO", "PKCS5", "ZERO", "RANDOM", "BIT") + * @returns {number[]} - Ciphertext as byte array + */ +export function encryptTwofish(message, key, iv, mode = "ECB", padding = "PKCS5") { + const messageLength = message.length; + if (messageLength === 0) return []; + + const keyData = generateSubkeys(key); + + // Apply padding for ECB/CBC modes + let paddedMessage; + if (mode === "ECB" || mode === "CBC") { + paddedMessage = applyPadding(message, padding, BLOCKSIZE); + } else { + // Stream modes (CFB, OFB, CTR) don't need padding + paddedMessage = [...message]; + } + + const cipherText = []; + + switch (mode) { + case "ECB": + for (let i = 0; i < paddedMessage.length; i += BLOCKSIZE) { + const block = paddedMessage.slice(i, i + BLOCKSIZE); + cipherText.push(...encryptBlock(block, keyData)); + } + break; + + case "CBC": { + let ivBlock = [...iv]; + for (let i = 0; i < paddedMessage.length; i += BLOCKSIZE) { + const block = paddedMessage.slice(i, i + BLOCKSIZE); + const xored = xorBlocks(block, ivBlock); + ivBlock = encryptBlock(xored, keyData); + cipherText.push(...ivBlock); + } + break; + } + + case "CFB": { + let ivBlock = [...iv]; + for (let i = 0; i < paddedMessage.length; i += BLOCKSIZE) { + const encrypted = encryptBlock(ivBlock, keyData); + const block = paddedMessage.slice(i, i + BLOCKSIZE); + ivBlock = xorBlocks(encrypted, block); + cipherText.push(...ivBlock); + } + return cipherText.slice(0, messageLength); + } + + case "OFB": { + let ivBlock = [...iv]; + for (let i = 0; i < paddedMessage.length; i += BLOCKSIZE) { + ivBlock = encryptBlock(ivBlock, keyData); + const block = paddedMessage.slice(i, i + BLOCKSIZE); + cipherText.push(...xorBlocks(ivBlock, block)); + } + return cipherText.slice(0, messageLength); + } + + case "CTR": { + let counter = [...iv]; + for (let i = 0; i < paddedMessage.length; i += BLOCKSIZE) { + const encrypted = encryptBlock(counter, keyData); + const block = paddedMessage.slice(i, i + BLOCKSIZE); + cipherText.push(...xorBlocks(encrypted, block)); + counter = incrementCounter(counter); + } + return cipherText.slice(0, messageLength); + } + + default: + throw new OperationError(`Invalid block cipher mode: ${mode}`); + } + + return cipherText; +} + +/** + * Decrypt using Twofish cipher with specified block mode + * + * @param {number[]} cipherText - Ciphertext as byte array + * @param {number[]} key - Key (16, 24, or 32 bytes) + * @param {number[]} iv - IV (16 bytes, not used for ECB) + * @param {string} mode - Block cipher mode ("ECB", "CBC", "CFB", "OFB", "CTR") + * @param {string} padding - Padding type ("NO", "PKCS5", "ZERO", "RANDOM", "BIT") + * @returns {number[]} - Plaintext as byte array + */ +export function decryptTwofish(cipherText, key, iv, mode = "ECB", padding = "PKCS5") { + const originalLength = cipherText.length; + if (originalLength === 0) return []; + + const keyData = generateSubkeys(key); + + if (mode === "ECB" || mode === "CBC") { + if ((originalLength % BLOCKSIZE) !== 0) + throw new OperationError(`Invalid ciphertext length: ${originalLength} bytes. Must be a multiple of 16.`); + } else { + // Pad for stream modes + while ((cipherText.length % BLOCKSIZE) !== 0) + cipherText.push(0); + } + + const plainText = []; + + switch (mode) { + case "ECB": + for (let i = 0; i < cipherText.length; i += BLOCKSIZE) { + const block = cipherText.slice(i, i + BLOCKSIZE); + plainText.push(...decryptBlock(block, keyData)); + } + break; + + case "CBC": { + let ivBlock = [...iv]; + for (let i = 0; i < cipherText.length; i += BLOCKSIZE) { + const block = cipherText.slice(i, i + BLOCKSIZE); + const decrypted = decryptBlock(block, keyData); + plainText.push(...xorBlocks(decrypted, ivBlock)); + ivBlock = block; + } + break; + } + + case "CFB": { + let ivBlock = [...iv]; + for (let i = 0; i < cipherText.length; i += BLOCKSIZE) { + const encrypted = encryptBlock(ivBlock, keyData); + const block = cipherText.slice(i, i + BLOCKSIZE); + plainText.push(...xorBlocks(encrypted, block)); + ivBlock = block; + } + return plainText.slice(0, originalLength); + } + + case "OFB": { + let ivBlock = [...iv]; + for (let i = 0; i < cipherText.length; i += BLOCKSIZE) { + ivBlock = encryptBlock(ivBlock, keyData); + const block = cipherText.slice(i, i + BLOCKSIZE); + plainText.push(...xorBlocks(ivBlock, block)); + } + return plainText.slice(0, originalLength); + } + + case "CTR": { + let counter = [...iv]; + for (let i = 0; i < cipherText.length; i += BLOCKSIZE) { + const encrypted = encryptBlock(counter, keyData); + const block = cipherText.slice(i, i + BLOCKSIZE); + plainText.push(...xorBlocks(encrypted, block)); + counter = incrementCounter(counter); + } + return plainText.slice(0, originalLength); + } + + default: + throw new OperationError(`Invalid block cipher mode: ${mode}`); + } + + // Remove padding for ECB/CBC modes + if (mode === "ECB" || mode === "CBC") { + return removePadding(plainText, padding, BLOCKSIZE); + } + + return plainText.slice(0, originalLength); +} diff --git a/src/core/operations/PRESENTDecrypt.mjs b/src/core/operations/PRESENTDecrypt.mjs new file mode 100644 index 0000000000..54d6299548 --- /dev/null +++ b/src/core/operations/PRESENTDecrypt.mjs @@ -0,0 +1,94 @@ +/** + * @author Medjedtxm + * @copyright Crown Copyright 2026 + * @license Apache-2.0 + */ + +import Operation from "../Operation.mjs"; +import Utils from "../Utils.mjs"; +import OperationError from "../errors/OperationError.mjs"; +import { toHex } from "../lib/Hex.mjs"; +import { decryptPRESENT } from "../lib/Present.mjs"; + +/** + * PRESENT Decrypt operation + */ +class PRESENTDecrypt extends Operation { + + /** + * PRESENTDecrypt constructor + */ + constructor() { + super(); + + this.name = "PRESENT Decrypt"; + this.module = "Ciphers"; + this.description = "PRESENT is an ultra-lightweight block cipher designed for constrained environments such as RFID tags and sensor networks. It operates on 64-bit blocks and supports 80-bit or 128-bit keys with 31 rounds. Standardised in ISO/IEC 29192-2:2019.

When using CBC mode, the PKCS#7 padding scheme is used."; + this.infoURL = "https://wikipedia.org/wiki/PRESENT_(cipher)"; + this.inputType = "string"; + this.outputType = "string"; + this.args = [ + { + "name": "Key", + "type": "toggleString", + "value": "", + "toggleValues": ["Hex", "UTF8", "Latin1", "Base64"] + }, + { + "name": "IV", + "type": "toggleString", + "value": "", + "toggleValues": ["Hex", "UTF8", "Latin1", "Base64"] + }, + { + "name": "Mode", + "type": "option", + "value": ["CBC", "ECB"] + }, + { + "name": "Input", + "type": "option", + "value": ["Hex", "Raw"] + }, + { + "name": "Output", + "type": "option", + "value": ["Raw", "Hex"] + }, + { + "name": "Padding", + "type": "option", + "value": ["PKCS5", "NO", "ZERO", "RANDOM", "BIT"] + } + ]; + } + + /** + * @param {string} input + * @param {Object[]} args + * @returns {string} + */ + run(input, args) { + const key = Utils.convertToByteArray(args[0].string, args[0].option), + iv = Utils.convertToByteArray(args[1].string, args[1].option), + [,, mode, inputType, outputType, padding] = args; + + if (key.length !== 10 && key.length !== 16) + throw new OperationError(`Invalid key length: ${key.length} bytes + +PRESENT uses a key length of 10 bytes (80 bits) or 16 bytes (128 bits).`); + + if (iv.length !== 8 && mode !== "ECB") + throw new OperationError(`Invalid IV length: ${iv.length} bytes + +PRESENT uses an IV length of 8 bytes (64 bits). +Make sure you have specified the type correctly (e.g. Hex vs UTF8).`); + + input = Utils.convertToByteArray(input, inputType); + const output = decryptPRESENT(input, key, iv, mode, padding); + return outputType === "Hex" ? toHex(output, "") : Utils.byteArrayToUtf8(output); + } + +} + +export default PRESENTDecrypt; diff --git a/src/core/operations/PRESENTEncrypt.mjs b/src/core/operations/PRESENTEncrypt.mjs new file mode 100644 index 0000000000..2a02c3d326 --- /dev/null +++ b/src/core/operations/PRESENTEncrypt.mjs @@ -0,0 +1,94 @@ +/** + * @author Medjedtxm + * @copyright Crown Copyright 2026 + * @license Apache-2.0 + */ + +import Operation from "../Operation.mjs"; +import Utils from "../Utils.mjs"; +import OperationError from "../errors/OperationError.mjs"; +import { toHex } from "../lib/Hex.mjs"; +import { encryptPRESENT } from "../lib/Present.mjs"; + +/** + * PRESENT Encrypt operation + */ +class PRESENTEncrypt extends Operation { + + /** + * PRESENTEncrypt constructor + */ + constructor() { + super(); + + this.name = "PRESENT Encrypt"; + this.module = "Ciphers"; + this.description = "PRESENT is an ultra-lightweight block cipher designed for constrained environments such as RFID tags and sensor networks. It operates on 64-bit blocks and supports 80-bit or 128-bit keys with 31 rounds. Standardised in ISO/IEC 29192-2:2019.

When using CBC mode, the PKCS#7 padding scheme is used."; + this.infoURL = "https://wikipedia.org/wiki/PRESENT_(cipher)"; + this.inputType = "string"; + this.outputType = "string"; + this.args = [ + { + "name": "Key", + "type": "toggleString", + "value": "", + "toggleValues": ["Hex", "UTF8", "Latin1", "Base64"] + }, + { + "name": "IV", + "type": "toggleString", + "value": "", + "toggleValues": ["Hex", "UTF8", "Latin1", "Base64"] + }, + { + "name": "Mode", + "type": "option", + "value": ["CBC", "ECB"] + }, + { + "name": "Input", + "type": "option", + "value": ["Raw", "Hex"] + }, + { + "name": "Output", + "type": "option", + "value": ["Hex", "Raw"] + }, + { + "name": "Padding", + "type": "option", + "value": ["PKCS5", "NO", "ZERO", "RANDOM", "BIT"] + } + ]; + } + + /** + * @param {string} input + * @param {Object[]} args + * @returns {string} + */ + run(input, args) { + const key = Utils.convertToByteArray(args[0].string, args[0].option), + iv = Utils.convertToByteArray(args[1].string, args[1].option), + [,, mode, inputType, outputType, padding] = args; + + if (key.length !== 10 && key.length !== 16) + throw new OperationError(`Invalid key length: ${key.length} bytes + +PRESENT uses a key length of 10 bytes (80 bits) or 16 bytes (128 bits).`); + + if (iv.length !== 8 && mode !== "ECB") + throw new OperationError(`Invalid IV length: ${iv.length} bytes + +PRESENT uses an IV length of 8 bytes (64 bits). +Make sure you have specified the type correctly (e.g. Hex vs UTF8).`); + + input = Utils.convertToByteArray(input, inputType); + const output = encryptPRESENT(input, key, iv, mode, padding); + return outputType === "Hex" ? toHex(output, "") : Utils.byteArrayToUtf8(output); + } + +} + +export default PRESENTEncrypt; diff --git a/src/core/operations/TwofishDecrypt.mjs b/src/core/operations/TwofishDecrypt.mjs new file mode 100644 index 0000000000..6d5d033c65 --- /dev/null +++ b/src/core/operations/TwofishDecrypt.mjs @@ -0,0 +1,94 @@ +/** + * @author Medjedtxm + * @copyright Crown Copyright 2026 + * @license Apache-2.0 + */ + +import Operation from "../Operation.mjs"; +import Utils from "../Utils.mjs"; +import OperationError from "../errors/OperationError.mjs"; +import { toHex } from "../lib/Hex.mjs"; +import { decryptTwofish } from "../lib/Twofish.mjs"; + +/** + * Twofish Decrypt operation + */ +class TwofishDecrypt extends Operation { + + /** + * TwofishDecrypt constructor + */ + constructor() { + super(); + + this.name = "Twofish Decrypt"; + this.module = "Ciphers"; + this.description = "Twofish is a symmetric key block cipher designed by Bruce Schneier. It was one of the five AES finalists. Twofish operates on 128-bit blocks and supports key sizes of 128, 192, or 256 bits with 16 rounds of a Feistel network.

When using CBC or ECB mode, the PKCS#7 padding scheme is used."; + this.infoURL = "https://wikipedia.org/wiki/Twofish"; + this.inputType = "string"; + this.outputType = "string"; + this.args = [ + { + "name": "Key", + "type": "toggleString", + "value": "", + "toggleValues": ["Hex", "UTF8", "Latin1", "Base64"] + }, + { + "name": "IV", + "type": "toggleString", + "value": "", + "toggleValues": ["Hex", "UTF8", "Latin1", "Base64"] + }, + { + "name": "Mode", + "type": "option", + "value": ["CBC", "CFB", "OFB", "CTR", "ECB"] + }, + { + "name": "Input", + "type": "option", + "value": ["Hex", "Raw"] + }, + { + "name": "Output", + "type": "option", + "value": ["Raw", "Hex"] + }, + { + "name": "Padding", + "type": "option", + "value": ["PKCS5", "NO", "ZERO", "RANDOM", "BIT"] + } + ]; + } + + /** + * @param {string} input + * @param {Object[]} args + * @returns {string} + */ + run(input, args) { + const key = Utils.convertToByteArray(args[0].string, args[0].option), + iv = Utils.convertToByteArray(args[1].string, args[1].option), + [,, mode, inputType, outputType, padding] = args; + + if (key.length !== 16 && key.length !== 24 && key.length !== 32) + throw new OperationError(`Invalid key length: ${key.length} bytes + +Twofish uses a key length of 16 bytes (128 bits), 24 bytes (192 bits), or 32 bytes (256 bits).`); + + if (iv.length !== 16 && mode !== "ECB") + throw new OperationError(`Invalid IV length: ${iv.length} bytes + +Twofish uses an IV length of 16 bytes (128 bits). +Make sure you have specified the type correctly (e.g. Hex vs UTF8).`); + + input = Utils.convertToByteArray(input, inputType); + const output = decryptTwofish(input, key, iv, mode, padding); + return outputType === "Hex" ? toHex(output, "") : Utils.byteArrayToUtf8(output); + } + +} + +export default TwofishDecrypt; diff --git a/src/core/operations/TwofishEncrypt.mjs b/src/core/operations/TwofishEncrypt.mjs new file mode 100644 index 0000000000..e8e3f16fa1 --- /dev/null +++ b/src/core/operations/TwofishEncrypt.mjs @@ -0,0 +1,94 @@ +/** + * @author Medjedtxm + * @copyright Crown Copyright 2026 + * @license Apache-2.0 + */ + +import Operation from "../Operation.mjs"; +import Utils from "../Utils.mjs"; +import OperationError from "../errors/OperationError.mjs"; +import { toHex } from "../lib/Hex.mjs"; +import { encryptTwofish } from "../lib/Twofish.mjs"; + +/** + * Twofish Encrypt operation + */ +class TwofishEncrypt extends Operation { + + /** + * TwofishEncrypt constructor + */ + constructor() { + super(); + + this.name = "Twofish Encrypt"; + this.module = "Ciphers"; + this.description = "Twofish is a symmetric key block cipher designed by Bruce Schneier. It was one of the five AES finalists. Twofish operates on 128-bit blocks and supports key sizes of 128, 192, or 256 bits with 16 rounds of a Feistel network.

When using CBC or ECB mode, the PKCS#7 padding scheme is used."; + this.infoURL = "https://wikipedia.org/wiki/Twofish"; + this.inputType = "string"; + this.outputType = "string"; + this.args = [ + { + "name": "Key", + "type": "toggleString", + "value": "", + "toggleValues": ["Hex", "UTF8", "Latin1", "Base64"] + }, + { + "name": "IV", + "type": "toggleString", + "value": "", + "toggleValues": ["Hex", "UTF8", "Latin1", "Base64"] + }, + { + "name": "Mode", + "type": "option", + "value": ["CBC", "CFB", "OFB", "CTR", "ECB"] + }, + { + "name": "Input", + "type": "option", + "value": ["Raw", "Hex"] + }, + { + "name": "Output", + "type": "option", + "value": ["Hex", "Raw"] + }, + { + "name": "Padding", + "type": "option", + "value": ["PKCS5", "NO", "ZERO", "RANDOM", "BIT"] + } + ]; + } + + /** + * @param {string} input + * @param {Object[]} args + * @returns {string} + */ + run(input, args) { + const key = Utils.convertToByteArray(args[0].string, args[0].option), + iv = Utils.convertToByteArray(args[1].string, args[1].option), + [,, mode, inputType, outputType, padding] = args; + + if (key.length !== 16 && key.length !== 24 && key.length !== 32) + throw new OperationError(`Invalid key length: ${key.length} bytes + +Twofish uses a key length of 16 bytes (128 bits), 24 bytes (192 bits), or 32 bytes (256 bits).`); + + if (iv.length !== 16 && mode !== "ECB") + throw new OperationError(`Invalid IV length: ${iv.length} bytes + +Twofish uses an IV length of 16 bytes (128 bits). +Make sure you have specified the type correctly (e.g. Hex vs UTF8).`); + + input = Utils.convertToByteArray(input, inputType); + const output = encryptTwofish(input, key, iv, mode, padding); + return outputType === "Hex" ? toHex(output, "") : Utils.byteArrayToUtf8(output); + } + +} + +export default TwofishEncrypt; diff --git a/tests/operations/tests/PRESENT.mjs b/tests/operations/tests/PRESENT.mjs new file mode 100644 index 0000000000..f581d22f04 --- /dev/null +++ b/tests/operations/tests/PRESENT.mjs @@ -0,0 +1,465 @@ +/** + * PRESENT cipher tests. + * + * Test vectors from the original PRESENT paper: + * "PRESENT: An Ultra-Lightweight Block Cipher" + * https://link.springer.com/chapter/10.1007/978-3-540-74735-2_31 + * https://www.iacr.org/archive/ches2007/47270450/47270450.pdf + * + * Note: PKCS5 padding adds an extra block when input is exactly block-aligned. + * Round-trip tests verify correct encryption/decryption behavior. + * + * @author Medjedtxm + * @copyright Crown Copyright 2026 + * @license Apache-2.0 + */ + +import TestRegister from "../../lib/TestRegister.mjs"; + +TestRegister.addTests([ + // ============================================================ + // OFFICIAL TEST VECTORS from the original PRESENT paper: + // "PRESENT: An Ultra-Lightweight Block Cipher" (Bogdanov et al., CHES 2007) + // https://link.springer.com/chapter/10.1007/978-3-540-74735-2_31 + // Table 3: Test Vectors + // ============================================================ + { + name: "PRESENT Official Vector 1: 80-bit zero key, zero plaintext", + input: "0000000000000000", + expectedOutput: "5579c1387b228445", + recipeConfig: [ + { + op: "PRESENT Encrypt", + args: [ + { string: "00000000000000000000", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Hex", "Hex", "NO" + ] + } + ] + }, + { + name: "PRESENT Official Vector 2: 80-bit all-ones key, zero plaintext", + input: "0000000000000000", + expectedOutput: "e72c46c0f5945049", + recipeConfig: [ + { + op: "PRESENT Encrypt", + args: [ + { string: "ffffffffffffffffffff", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Hex", "Hex", "NO" + ] + } + ] + }, + { + name: "PRESENT Official Vector 3: 80-bit zero key, all-ones plaintext", + input: "ffffffffffffffff", + expectedOutput: "a112ffc72f68417b", + recipeConfig: [ + { + op: "PRESENT Encrypt", + args: [ + { string: "00000000000000000000", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Hex", "Hex", "NO" + ] + } + ] + }, + { + name: "PRESENT Official Vector 4: 80-bit all-ones key, all-ones plaintext", + input: "ffffffffffffffff", + expectedOutput: "3333dcd3213210d2", + recipeConfig: [ + { + op: "PRESENT Encrypt", + args: [ + { string: "ffffffffffffffffffff", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Hex", "Hex", "NO" + ] + } + ] + }, + { + name: "PRESENT Official Vector 5: 128-bit zero key, zero plaintext", + input: "0000000000000000", + expectedOutput: "96db702a2e6900af", + recipeConfig: [ + { + op: "PRESENT Encrypt", + args: [ + { string: "00000000000000000000000000000000", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Hex", "Hex", "NO" + ] + } + ] + }, + { + name: "PRESENT Official Vector 6: 128-bit key (SageMath reference)", + input: "0123456789abcdef", + expectedOutput: "0e9d28685e671dd6", + recipeConfig: [ + { + op: "PRESENT Encrypt", + args: [ + { string: "0123456789abcdef0123456789abcdef", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Hex", "Hex", "NO" + ] + } + ] + }, + // Decrypt verification of official vectors + { + name: "PRESENT Official Vector 1 Decrypt: 80-bit zero key", + input: "5579c1387b228445", + expectedOutput: "0000000000000000", + recipeConfig: [ + { + op: "PRESENT Decrypt", + args: [ + { string: "00000000000000000000", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Hex", "Hex", "NO" + ] + } + ] + }, + { + name: "PRESENT Official Vector 4 Decrypt: 80-bit all-ones key", + input: "3333dcd3213210d2", + expectedOutput: "ffffffffffffffff", + recipeConfig: [ + { + op: "PRESENT Decrypt", + args: [ + { string: "ffffffffffffffffffff", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Hex", "Hex", "NO" + ] + } + ] + }, + { + name: "PRESENT Official Vector 5 Decrypt: 128-bit zero key", + input: "96db702a2e6900af", + expectedOutput: "0000000000000000", + recipeConfig: [ + { + op: "PRESENT Decrypt", + args: [ + { string: "00000000000000000000000000000000", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Hex", "Hex", "NO" + ] + } + ] + }, + { + name: "PRESENT Official Vector 6 Decrypt: 128-bit key (SageMath reference)", + input: "0e9d28685e671dd6", + expectedOutput: "0123456789abcdef", + recipeConfig: [ + { + op: "PRESENT Decrypt", + args: [ + { string: "0123456789abcdef0123456789abcdef", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Hex", "Hex", "NO" + ] + } + ] + }, + // ============================================================ + // Round-trip tests - These verify encryption and decryption work correctly + // ============================================================ + { + name: "PRESENT Round-trip: ECB 80-bit key, short message", + input: "Hello!!!", + expectedOutput: "Hello!!!", + recipeConfig: [ + { + op: "PRESENT Encrypt", + args: [ + { string: "00112233445566778899", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Raw", "Hex", "PKCS5" + ] + }, + { + op: "PRESENT Decrypt", + args: [ + { string: "00112233445566778899", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Hex", "Raw", "PKCS5" + ] + } + ] + }, + { + name: "PRESENT Round-trip: CBC 80-bit key, long message", + input: "The quick brown fox jumps over the lazy dog", + expectedOutput: "The quick brown fox jumps over the lazy dog", + recipeConfig: [ + { + op: "PRESENT Encrypt", + args: [ + { string: "aabbccddeeff00112233", option: "Hex" }, + { string: "0011223344556677", option: "Hex" }, + "CBC", "Raw", "Hex", "PKCS5" + ] + }, + { + op: "PRESENT Decrypt", + args: [ + { string: "aabbccddeeff00112233", option: "Hex" }, + { string: "0011223344556677", option: "Hex" }, + "CBC", "Hex", "Raw", "PKCS5" + ] + } + ] + }, + { + name: "PRESENT Round-trip: ECB 128-bit key", + input: "Testing PRESENT cipher with 128-bit key", + expectedOutput: "Testing PRESENT cipher with 128-bit key", + recipeConfig: [ + { + op: "PRESENT Encrypt", + args: [ + { string: "00112233445566778899aabbccddeeff", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Raw", "Hex", "PKCS5" + ] + }, + { + op: "PRESENT Decrypt", + args: [ + { string: "00112233445566778899aabbccddeeff", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Hex", "Raw", "PKCS5" + ] + } + ] + }, + { + name: "PRESENT Round-trip: CBC 128-bit key", + input: "PRESENT is an ultra-lightweight block cipher!", + expectedOutput: "PRESENT is an ultra-lightweight block cipher!", + recipeConfig: [ + { + op: "PRESENT Encrypt", + args: [ + { string: "ffeeddccbbaa99887766554433221100", option: "Hex" }, + { string: "8877665544332211", option: "Hex" }, + "CBC", "Raw", "Hex", "PKCS5" + ] + }, + { + op: "PRESENT Decrypt", + args: [ + { string: "ffeeddccbbaa99887766554433221100", option: "Hex" }, + { string: "8877665544332211", option: "Hex" }, + "CBC", "Hex", "Raw", "PKCS5" + ] + } + ] + }, + { + name: "PRESENT Round-trip: UTF8 key (10 bytes)", + input: "Secret message", + expectedOutput: "Secret message", + recipeConfig: [ + { + op: "PRESENT Encrypt", + args: [ + { string: "mypassword", option: "UTF8" }, + { string: "initvect", option: "UTF8" }, + "CBC", "Raw", "Hex", "PKCS5" + ] + }, + { + op: "PRESENT Decrypt", + args: [ + { string: "mypassword", option: "UTF8" }, + { string: "initvect", option: "UTF8" }, + "CBC", "Hex", "Raw", "PKCS5" + ] + } + ] + }, + + // Encryption consistency tests - verify same input always produces same output + { + name: "PRESENT Encrypt: 80-bit zero key consistency", + input: "TestData", + expectedOutput: "b78cfea5ffcd89f265585a6ce7312131", + recipeConfig: [ + { + op: "PRESENT Encrypt", + args: [ + { string: "00000000000000000000", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Raw", "Hex", "PKCS5" + ] + } + ] + }, + { + name: "PRESENT Encrypt: 128-bit zero key consistency", + input: "TestData", + expectedOutput: "e127a24e38de2c36407e794ef5dffefd", + recipeConfig: [ + { + op: "PRESENT Encrypt", + args: [ + { string: "00000000000000000000000000000000", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Raw", "Hex", "PKCS5" + ] + } + ] + }, + { + name: "PRESENT Round-trip: Various lengths 1 byte", + input: "A", + expectedOutput: "A", + recipeConfig: [ + { + op: "PRESENT Encrypt", + args: [ + { string: "00112233445566778899", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Raw", "Hex", "PKCS5" + ] + }, + { + op: "PRESENT Decrypt", + args: [ + { string: "00112233445566778899", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Hex", "Raw", "PKCS5" + ] + } + ] + }, + { + name: "PRESENT Round-trip: Various lengths 7 bytes", + input: "1234567", + expectedOutput: "1234567", + recipeConfig: [ + { + op: "PRESENT Encrypt", + args: [ + { string: "00112233445566778899", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Raw", "Hex", "PKCS5" + ] + }, + { + op: "PRESENT Decrypt", + args: [ + { string: "00112233445566778899", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Hex", "Raw", "PKCS5" + ] + } + ] + }, + { + name: "PRESENT Round-trip: Various lengths 8 bytes (exact block)", + input: "12345678", + expectedOutput: "12345678", + recipeConfig: [ + { + op: "PRESENT Encrypt", + args: [ + { string: "00112233445566778899", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Raw", "Hex", "PKCS5" + ] + }, + { + op: "PRESENT Decrypt", + args: [ + { string: "00112233445566778899", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Hex", "Raw", "PKCS5" + ] + } + ] + }, + { + name: "PRESENT Round-trip: Various lengths 9 bytes", + input: "123456789", + expectedOutput: "123456789", + recipeConfig: [ + { + op: "PRESENT Encrypt", + args: [ + { string: "00112233445566778899", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Raw", "Hex", "PKCS5" + ] + }, + { + op: "PRESENT Decrypt", + args: [ + { string: "00112233445566778899", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Hex", "Raw", "PKCS5" + ] + } + ] + }, + { + name: "PRESENT Round-trip: Various lengths 16 bytes (two blocks)", + input: "1234567890ABCDEF", + expectedOutput: "1234567890ABCDEF", + recipeConfig: [ + { + op: "PRESENT Encrypt", + args: [ + { string: "00112233445566778899", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Raw", "Hex", "PKCS5" + ] + }, + { + op: "PRESENT Decrypt", + args: [ + { string: "00112233445566778899", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Hex", "Raw", "PKCS5" + ] + } + ] + }, + { + name: "PRESENT Round-trip: Binary data", + input: "\x00\x01\x02\x03\x04\x05\x06\x07", + expectedOutput: "\x00\x01\x02\x03\x04\x05\x06\x07", + recipeConfig: [ + { + op: "PRESENT Encrypt", + args: [ + { string: "ffeeddccbbaa99887766", option: "Hex" }, + { string: "0011223344556677", option: "Hex" }, + "CBC", "Raw", "Hex", "PKCS5" + ] + }, + { + op: "PRESENT Decrypt", + args: [ + { string: "ffeeddccbbaa99887766", option: "Hex" }, + { string: "0011223344556677", option: "Hex" }, + "CBC", "Hex", "Raw", "PKCS5" + ] + } + ] + } +]); diff --git a/tests/operations/tests/Twofish.mjs b/tests/operations/tests/Twofish.mjs new file mode 100644 index 0000000000..d92fd0eafb --- /dev/null +++ b/tests/operations/tests/Twofish.mjs @@ -0,0 +1,486 @@ +/** + * Twofish cipher tests. + * + * Test vectors from the official Twofish paper: + * https://www.schneier.com/academic/twofish/ + * + * Note: PKCS5 padding adds an extra block when input is exactly block-aligned. + * Round-trip tests verify correct encryption/decryption behavior. + * + * @author Medjedtxm + * @copyright Crown Copyright 2026 + * @license Apache-2.0 + */ + +import TestRegister from "../../lib/TestRegister.mjs"; + +TestRegister.addTests([ + // ============================================================ + // OFFICIAL TEST VECTORS from Bruce Schneier's Twofish paper: + // https://www.schneier.com/academic/twofish/ + // https://www.schneier.com/wp-content/uploads/2015/12/ecb_ival.txt + // ============================================================ + { + name: "Twofish Official Vector: 128-bit zero key, zero plaintext", + input: "00000000000000000000000000000000", + expectedOutput: "9f589f5cf6122c32b6bfec2f2ae8c35a", + recipeConfig: [ + { + op: "Twofish Encrypt", + args: [ + { string: "00000000000000000000000000000000", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Hex", "Hex", "NO" + ] + } + ] + }, + { + name: "Twofish Official Vector: 192-bit zero key, zero plaintext", + input: "00000000000000000000000000000000", + expectedOutput: "efa71f788965bd4453f860178fc19101", + recipeConfig: [ + { + op: "Twofish Encrypt", + args: [ + { string: "000000000000000000000000000000000000000000000000", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Hex", "Hex", "NO" + ] + } + ] + }, + { + name: "Twofish Official Vector: 256-bit zero key, zero plaintext", + input: "00000000000000000000000000000000", + expectedOutput: "57ff739d4dc92c1bd7fc01700cc8216f", + recipeConfig: [ + { + op: "Twofish Encrypt", + args: [ + { string: "0000000000000000000000000000000000000000000000000000000000000000", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Hex", "Hex", "NO" + ] + } + ] + }, + // Decrypt verification of official vectors + { + name: "Twofish Official Vector Decrypt: 128-bit zero key", + input: "9f589f5cf6122c32b6bfec2f2ae8c35a", + expectedOutput: "00000000000000000000000000000000", + recipeConfig: [ + { + op: "Twofish Decrypt", + args: [ + { string: "00000000000000000000000000000000", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Hex", "Hex", "NO" + ] + } + ] + }, + // ============================================================ + // Round-trip tests for ECB mode with various key sizes + // ============================================================ + { + name: "Twofish Round-trip: ECB 128-bit key", + input: "Hello, World!!!", + expectedOutput: "Hello, World!!!", + recipeConfig: [ + { + op: "Twofish Encrypt", + args: [ + { string: "00112233445566778899aabbccddeeff", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Raw", "Hex", "PKCS5" + ] + }, + { + op: "Twofish Decrypt", + args: [ + { string: "00112233445566778899aabbccddeeff", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Hex", "Raw", "PKCS5" + ] + } + ] + }, + { + name: "Twofish Round-trip: ECB 192-bit key", + input: "Testing Twofish with 192-bit key", + expectedOutput: "Testing Twofish with 192-bit key", + recipeConfig: [ + { + op: "Twofish Encrypt", + args: [ + { string: "000102030405060708090a0b0c0d0e0f1011121314151617", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Raw", "Hex", "PKCS5" + ] + }, + { + op: "Twofish Decrypt", + args: [ + { string: "000102030405060708090a0b0c0d0e0f1011121314151617", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Hex", "Raw", "PKCS5" + ] + } + ] + }, + { + name: "Twofish Round-trip: ECB 256-bit key", + input: "Testing Twofish with 256-bit key encryption", + expectedOutput: "Testing Twofish with 256-bit key encryption", + recipeConfig: [ + { + op: "Twofish Encrypt", + args: [ + { string: "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Raw", "Hex", "PKCS5" + ] + }, + { + op: "Twofish Decrypt", + args: [ + { string: "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Hex", "Raw", "PKCS5" + ] + } + ] + }, + + // Round-trip tests for CBC mode + { + name: "Twofish Round-trip: CBC 128-bit key", + input: "The quick brown fox jumps over the lazy dog", + expectedOutput: "The quick brown fox jumps over the lazy dog", + recipeConfig: [ + { + op: "Twofish Encrypt", + args: [ + { string: "00112233445566778899aabbccddeeff", option: "Hex" }, + { string: "ffeeddccbbaa99887766554433221100", option: "Hex" }, + "CBC", "Raw", "Hex", "PKCS5" + ] + }, + { + op: "Twofish Decrypt", + args: [ + { string: "00112233445566778899aabbccddeeff", option: "Hex" }, + { string: "ffeeddccbbaa99887766554433221100", option: "Hex" }, + "CBC", "Hex", "Raw", "PKCS5" + ] + } + ] + }, + { + name: "Twofish Round-trip: CBC 192-bit key", + input: "Testing Twofish with 192-bit key in CBC mode", + expectedOutput: "Testing Twofish with 192-bit key in CBC mode", + recipeConfig: [ + { + op: "Twofish Encrypt", + args: [ + { string: "000102030405060708090a0b0c0d0e0f1011121314151617", option: "Hex" }, + { string: "ffeeddccbbaa99887766554433221100", option: "Hex" }, + "CBC", "Raw", "Hex", "PKCS5" + ] + }, + { + op: "Twofish Decrypt", + args: [ + { string: "000102030405060708090a0b0c0d0e0f1011121314151617", option: "Hex" }, + { string: "ffeeddccbbaa99887766554433221100", option: "Hex" }, + "CBC", "Hex", "Raw", "PKCS5" + ] + } + ] + }, + { + name: "Twofish Round-trip: CBC 256-bit key", + input: "Testing Twofish with 256-bit key in CBC mode", + expectedOutput: "Testing Twofish with 256-bit key in CBC mode", + recipeConfig: [ + { + op: "Twofish Encrypt", + args: [ + { string: "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", option: "Hex" }, + { string: "ffeeddccbbaa99887766554433221100", option: "Hex" }, + "CBC", "Raw", "Hex", "PKCS5" + ] + }, + { + op: "Twofish Decrypt", + args: [ + { string: "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", option: "Hex" }, + { string: "ffeeddccbbaa99887766554433221100", option: "Hex" }, + "CBC", "Hex", "Raw", "PKCS5" + ] + } + ] + }, + + // Round-trip tests for CFB mode + { + name: "Twofish Round-trip: CFB 128-bit key", + input: "Testing Twofish CFB mode encryption", + expectedOutput: "Testing Twofish CFB mode encryption", + recipeConfig: [ + { + op: "Twofish Encrypt", + args: [ + { string: "deadbeefcafebabe0123456789abcdef", option: "Hex" }, + { string: "0102030405060708090a0b0c0d0e0f10", option: "Hex" }, + "CFB", "Raw", "Hex", "PKCS5" + ] + }, + { + op: "Twofish Decrypt", + args: [ + { string: "deadbeefcafebabe0123456789abcdef", option: "Hex" }, + { string: "0102030405060708090a0b0c0d0e0f10", option: "Hex" }, + "CFB", "Hex", "Raw", "PKCS5" + ] + } + ] + }, + + // Round-trip tests for OFB mode + { + name: "Twofish Round-trip: OFB 128-bit key", + input: "Testing Twofish OFB mode encryption", + expectedOutput: "Testing Twofish OFB mode encryption", + recipeConfig: [ + { + op: "Twofish Encrypt", + args: [ + { string: "00112233445566778899aabbccddeeff", option: "Hex" }, + { string: "ffeeddccbbaa99887766554433221100", option: "Hex" }, + "OFB", "Raw", "Hex", "PKCS5" + ] + }, + { + op: "Twofish Decrypt", + args: [ + { string: "00112233445566778899aabbccddeeff", option: "Hex" }, + { string: "ffeeddccbbaa99887766554433221100", option: "Hex" }, + "OFB", "Hex", "Raw", "PKCS5" + ] + } + ] + }, + + // Round-trip tests for CTR mode + { + name: "Twofish Round-trip: CTR 128-bit key", + input: "Testing Twofish CTR mode encryption", + expectedOutput: "Testing Twofish CTR mode encryption", + recipeConfig: [ + { + op: "Twofish Encrypt", + args: [ + { string: "00112233445566778899aabbccddeeff", option: "Hex" }, + { string: "00000000000000000000000000000001", option: "Hex" }, + "CTR", "Raw", "Hex", "PKCS5" + ] + }, + { + op: "Twofish Decrypt", + args: [ + { string: "00112233445566778899aabbccddeeff", option: "Hex" }, + { string: "00000000000000000000000000000001", option: "Hex" }, + "CTR", "Hex", "Raw", "PKCS5" + ] + } + ] + }, + + // UTF8 key tests + { + name: "Twofish Round-trip: UTF8 key (16 bytes)", + input: "Secret message!", + expectedOutput: "Secret message!", + recipeConfig: [ + { + op: "Twofish Encrypt", + args: [ + { string: "MySecretPassword", option: "UTF8" }, + { string: "InitVectorHere!!", option: "UTF8" }, + "CBC", "Raw", "Hex", "PKCS5" + ] + }, + { + op: "Twofish Decrypt", + args: [ + { string: "MySecretPassword", option: "UTF8" }, + { string: "InitVectorHere!!", option: "UTF8" }, + "CBC", "Hex", "Raw", "PKCS5" + ] + } + ] + }, + + // Various input length tests + { + name: "Twofish Round-trip: 1 byte input", + input: "A", + expectedOutput: "A", + recipeConfig: [ + { + op: "Twofish Encrypt", + args: [ + { string: "00112233445566778899aabbccddeeff", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Raw", "Hex", "PKCS5" + ] + }, + { + op: "Twofish Decrypt", + args: [ + { string: "00112233445566778899aabbccddeeff", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Hex", "Raw", "PKCS5" + ] + } + ] + }, + { + name: "Twofish Round-trip: 15 byte input", + input: "123456789012345", + expectedOutput: "123456789012345", + recipeConfig: [ + { + op: "Twofish Encrypt", + args: [ + { string: "00112233445566778899aabbccddeeff", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Raw", "Hex", "PKCS5" + ] + }, + { + op: "Twofish Decrypt", + args: [ + { string: "00112233445566778899aabbccddeeff", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Hex", "Raw", "PKCS5" + ] + } + ] + }, + { + name: "Twofish Round-trip: 16 byte input (exact block)", + input: "1234567890123456", + expectedOutput: "1234567890123456", + recipeConfig: [ + { + op: "Twofish Encrypt", + args: [ + { string: "00112233445566778899aabbccddeeff", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Raw", "Hex", "PKCS5" + ] + }, + { + op: "Twofish Decrypt", + args: [ + { string: "00112233445566778899aabbccddeeff", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Hex", "Raw", "PKCS5" + ] + } + ] + }, + { + name: "Twofish Round-trip: 17 byte input", + input: "12345678901234567", + expectedOutput: "12345678901234567", + recipeConfig: [ + { + op: "Twofish Encrypt", + args: [ + { string: "00112233445566778899aabbccddeeff", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Raw", "Hex", "PKCS5" + ] + }, + { + op: "Twofish Decrypt", + args: [ + { string: "00112233445566778899aabbccddeeff", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Hex", "Raw", "PKCS5" + ] + } + ] + }, + { + name: "Twofish Round-trip: 32 byte input (two blocks)", + input: "12345678901234567890123456789012", + expectedOutput: "12345678901234567890123456789012", + recipeConfig: [ + { + op: "Twofish Encrypt", + args: [ + { string: "00112233445566778899aabbccddeeff", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Raw", "Hex", "PKCS5" + ] + }, + { + op: "Twofish Decrypt", + args: [ + { string: "00112233445566778899aabbccddeeff", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Hex", "Raw", "PKCS5" + ] + } + ] + }, + + // Binary data test + { + name: "Twofish Round-trip: Binary data", + input: "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f", + expectedOutput: "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f", + recipeConfig: [ + { + op: "Twofish Encrypt", + args: [ + { string: "ffeeddccbbaa99887766554433221100", option: "Hex" }, + { string: "00112233445566778899aabbccddeeff", option: "Hex" }, + "CBC", "Raw", "Hex", "PKCS5" + ] + }, + { + op: "Twofish Decrypt", + args: [ + { string: "ffeeddccbbaa99887766554433221100", option: "Hex" }, + { string: "00112233445566778899aabbccddeeff", option: "Hex" }, + "CBC", "Hex", "Raw", "PKCS5" + ] + } + ] + }, + + // Consistency test - same input should always produce same output + { + name: "Twofish Encrypt: 128-bit key consistency test", + input: "TestData12345678", + expectedOutput: "8aed2d3a85dc3e0b663ba1fe1fdaf056771d591428af301d69fa1e227d083527", + recipeConfig: [ + { + op: "Twofish Encrypt", + args: [ + { string: "00000000000000000000000000000000", option: "Hex" }, + { string: "", option: "Hex" }, + "ECB", "Raw", "Hex", "PKCS5" + ] + } + ] + } +]); From 002ed911b1a39f303b70246ac0ebf455a91c6d0f Mon Sep 17 00:00:00 2001 From: Thomas M <44269971+thomasxm@users.noreply.github.com> Date: Sun, 5 Jul 2026 13:22:27 +0100 Subject: [PATCH 2/2] feat: add TEA and XTEA block ciphers (#2225) --- src/core/config/Categories.json | 4 + src/core/lib/TEA.mjs | 494 ++++++++++++++++++++++++ src/core/operations/TEADecrypt.mjs | 98 +++++ src/core/operations/TEAEncrypt.mjs | 98 +++++ src/core/operations/XTEADecrypt.mjs | 110 ++++++ src/core/operations/XTEAEncrypt.mjs | 110 ++++++ tests/operations/tests/TEA.mjs | 566 ++++++++++++++++++++++++++++ 7 files changed, 1480 insertions(+) create mode 100644 src/core/lib/TEA.mjs create mode 100644 src/core/operations/TEADecrypt.mjs create mode 100644 src/core/operations/TEAEncrypt.mjs create mode 100644 src/core/operations/XTEADecrypt.mjs create mode 100644 src/core/operations/XTEAEncrypt.mjs create mode 100644 tests/operations/tests/TEA.mjs diff --git a/src/core/config/Categories.json b/src/core/config/Categories.json index 8c64c398d5..c652ed480d 100644 --- a/src/core/config/Categories.json +++ b/src/core/config/Categories.json @@ -135,6 +135,10 @@ "XOR Brute Force", "Vigenère Encode", "Vigenère Decode", + "TEA Encrypt", + "TEA Decrypt", + "XTEA Encrypt", + "XTEA Decrypt", "XXTEA Encrypt", "XXTEA Decrypt", "To Morse Code", diff --git a/src/core/lib/TEA.mjs b/src/core/lib/TEA.mjs new file mode 100644 index 0000000000..d2027c2d94 --- /dev/null +++ b/src/core/lib/TEA.mjs @@ -0,0 +1,494 @@ +/** + * TEA and XTEA block cipher implementation. + * + * TEA (Tiny Encryption Algorithm) — Wheeler & Needham, 1994. + * XTEA (Extended TEA) — Wheeler & Needham, 1997. + * + * Both operate on 64-bit blocks with 128-bit keys. + * TEA uses 32 cycles (64 Feistel rounds). + * XTEA uses 32 cycles (64 Feistel rounds) with improved key schedule. + * + * References: + * https://en.wikipedia.org/wiki/Tiny_Encryption_Algorithm + * https://en.wikipedia.org/wiki/XTEA + * https://www.cix.co.uk/~klockstone/teavect.htm + * + * @author Medjedtxm + * @copyright Crown Copyright 2026 + * @license Apache-2.0 + */ + +import OperationError from "../errors/OperationError.mjs"; + +/** TEA/XTEA constants */ +const DELTA = 0x9E3779B9; +const BLOCK_SIZE = 8; // 64-bit block = 8 bytes +const ROUNDS = 32; // 32 cycles + +/** + * Convert byte array to array of 32-bit unsigned integers (big-endian) + * @param {number[]} bytes + * @returns {number[]} + */ +function bytesToUint32(bytes) { + const words = []; + for (let i = 0; i < bytes.length; i += 4) { + words.push( + ((bytes[i] << 24) | (bytes[i + 1] << 16) | + (bytes[i + 2] << 8) | bytes[i + 3]) >>> 0 + ); + } + return words; +} + +/** + * Convert array of 32-bit unsigned integers to byte array (big-endian) + * @param {number[]} words + * @returns {number[]} + */ +function uint32ToBytes(words) { + const bytes = []; + for (const w of words) { + bytes.push((w >>> 24) & 0xFF); + bytes.push((w >>> 16) & 0xFF); + bytes.push((w >>> 8) & 0xFF); + bytes.push(w & 0xFF); + } + return bytes; +} + +/** + * TEA encrypt a single 64-bit block + * Reference: Wheeler & Needham, 1994 + * + * @param {number[]} block - 8 bytes (plaintext) + * @param {number[]} key - 16 bytes (128-bit key) + * @returns {number[]} - 8 bytes (ciphertext) + */ +function teaEncryptBlock(block, key) { + const v = bytesToUint32(block); + const k = bytesToUint32(key); + let v0 = v[0], v1 = v[1]; + let sum = 0; + + for (let i = 0; i < ROUNDS; i++) { + sum = (sum + DELTA) >>> 0; + v0 = (v0 + ((((v1 << 4) + k[0]) ^ (v1 + sum) ^ ((v1 >>> 5) + k[1])))) >>> 0; + v1 = (v1 + ((((v0 << 4) + k[2]) ^ (v0 + sum) ^ ((v0 >>> 5) + k[3])))) >>> 0; + } + + return uint32ToBytes([v0, v1]); +} + +/** + * TEA decrypt a single 64-bit block + * + * @param {number[]} block - 8 bytes (ciphertext) + * @param {number[]} key - 16 bytes (128-bit key) + * @returns {number[]} - 8 bytes (plaintext) + */ +function teaDecryptBlock(block, key) { + const v = bytesToUint32(block); + const k = bytesToUint32(key); + let v0 = v[0], v1 = v[1]; + let sum = (DELTA * ROUNDS) >>> 0; + + for (let i = 0; i < ROUNDS; i++) { + v1 = (v1 - ((((v0 << 4) + k[2]) ^ (v0 + sum) ^ ((v0 >>> 5) + k[3])))) >>> 0; + v0 = (v0 - ((((v1 << 4) + k[0]) ^ (v1 + sum) ^ ((v1 >>> 5) + k[1])))) >>> 0; + sum = (sum - DELTA) >>> 0; + } + + return uint32ToBytes([v0, v1]); +} + +/** + * XTEA encrypt a single 64-bit block + * Reference: Wheeler & Needham, 1997 + * + * @param {number[]} block - 8 bytes (plaintext) + * @param {number[]} key - 16 bytes (128-bit key) + * @param {number} rounds - Number of rounds (default 32) + * @returns {number[]} - 8 bytes (ciphertext) + */ +function xteaEncryptBlock(block, key, rounds) { + const v = bytesToUint32(block); + const k = bytesToUint32(key); + let v0 = v[0], v1 = v[1]; + let sum = 0; + + for (let i = 0; i < rounds; i++) { + v0 = (v0 + ((((v1 << 4) ^ (v1 >>> 5)) + v1) ^ (sum + k[sum & 3]))) >>> 0; + sum = (sum + DELTA) >>> 0; + v1 = (v1 + ((((v0 << 4) ^ (v0 >>> 5)) + v0) ^ (sum + k[(sum >>> 11) & 3]))) >>> 0; + } + + return uint32ToBytes([v0, v1]); +} + +/** + * XTEA decrypt a single 64-bit block + * + * @param {number[]} block - 8 bytes (ciphertext) + * @param {number[]} key - 16 bytes (128-bit key) + * @param {number} rounds - Number of rounds (default 32) + * @returns {number[]} - 8 bytes (plaintext) + */ +function xteaDecryptBlock(block, key, rounds) { + const v = bytesToUint32(block); + const k = bytesToUint32(key); + let v0 = v[0], v1 = v[1]; + let sum = (DELTA * rounds) >>> 0; + + for (let i = 0; i < rounds; i++) { + v1 = (v1 - ((((v0 << 4) ^ (v0 >>> 5)) + v0) ^ (sum + k[(sum >>> 11) & 3]))) >>> 0; + sum = (sum - DELTA) >>> 0; + v0 = (v0 - ((((v1 << 4) ^ (v1 >>> 5)) + v1) ^ (sum + k[sum & 3]))) >>> 0; + } + + return uint32ToBytes([v0, v1]); +} + +/** + * XOR two byte arrays of equal length + * @param {number[]} a + * @param {number[]} b + * @returns {number[]} + */ +function xorBlocks(a, b) { + return a.map((byte, i) => byte ^ b[i]); +} + +/** + * Increment a byte array as a big-endian counter + * @param {number[]} counter + * @returns {number[]} + */ +function incrementCounter(counter) { + const result = [...counter]; + for (let i = result.length - 1; i >= 0; i--) { + result[i] = (result[i] + 1) & 0xFF; + if (result[i] !== 0) break; + } + return result; +} + +/** + * Apply padding to message + * @param {number[]} message + * @param {string} padding - "NO", "PKCS5", "ZERO", "RANDOM", "BIT" + * @returns {number[]} + */ +function applyPadding(message, padding) { + const remainder = message.length % BLOCK_SIZE; + if (remainder === 0 && padding !== "PKCS5") return [...message]; + + const nPadding = (remainder === 0 && padding === "PKCS5") ? + BLOCK_SIZE : + BLOCK_SIZE - remainder; + + if (nPadding === 0) return [...message]; + + const padded = [...message]; + + switch (padding) { + case "NO": + throw new OperationError( + `No padding requested but input length (${message.length} bytes) is not a multiple of ${BLOCK_SIZE} bytes.` + ); + case "PKCS5": + for (let i = 0; i < nPadding; i++) padded.push(nPadding); + break; + case "ZERO": + for (let i = 0; i < nPadding; i++) padded.push(0); + break; + case "RANDOM": + for (let i = 0; i < nPadding; i++) padded.push(Math.floor(Math.random() * 256)); + break; + case "BIT": + padded.push(0x80); + for (let i = 1; i < nPadding; i++) padded.push(0); + break; + default: + throw new OperationError(`Unknown padding type: ${padding}`); + } + + return padded; +} + +/** + * Remove padding from message + * @param {number[]} message + * @param {string} padding + * @returns {number[]} + */ +function removePadding(message, padding) { + if (message.length === 0) return message; + + switch (padding) { + case "NO": + case "ZERO": + case "RANDOM": + return message; + + case "PKCS5": { + const padByte = message[message.length - 1]; + if (padByte > 0 && padByte <= BLOCK_SIZE) { + for (let i = 0; i < padByte; i++) { + if (message[message.length - 1 - i] !== padByte) { + throw new OperationError("Invalid PKCS#5 padding."); + } + } + return message.slice(0, message.length - padByte); + } + throw new OperationError("Invalid PKCS#5 padding."); + } + + case "BIT": { + for (let i = message.length - 1; i >= 0; i--) { + if (message[i] === 0x80) return message.slice(0, i); + if (message[i] !== 0) throw new OperationError("Invalid BIT padding."); + } + throw new OperationError("Invalid BIT padding."); + } + + default: + throw new OperationError(`Unknown padding type: ${padding}`); + } +} + +/** + * Encrypt with block cipher modes + * + * @param {number[]} message - Plaintext bytes + * @param {number[]} key - 16-byte key + * @param {number[]} iv - 8-byte IV (ignored for ECB) + * @param {string} mode - "ECB", "CBC", "CFB", "OFB", "CTR" + * @param {string} padding - "PKCS5", "NO", "ZERO", "RANDOM", "BIT" + * @param {Function} encryptBlockFn - Block encrypt function + * @returns {number[]} - Ciphertext bytes + */ +function encryptWithMode(message, key, iv, mode, padding, encryptBlockFn) { + const messageLength = message.length; + if (messageLength === 0) return []; + + let data; + if (mode === "ECB" || mode === "CBC") { + data = applyPadding(message, padding); + } else { + data = [...message]; + } + + const cipherText = []; + + switch (mode) { + case "ECB": + for (let i = 0; i < data.length; i += BLOCK_SIZE) { + cipherText.push(...encryptBlockFn(data.slice(i, i + BLOCK_SIZE), key)); + } + break; + + case "CBC": { + let ivBlock = [...iv]; + for (let i = 0; i < data.length; i += BLOCK_SIZE) { + const block = data.slice(i, i + BLOCK_SIZE); + const xored = xorBlocks(block, ivBlock); + ivBlock = encryptBlockFn(xored, key); + cipherText.push(...ivBlock); + } + break; + } + + case "CFB": { + let ivBlock = [...iv]; + for (let i = 0; i < data.length; i += BLOCK_SIZE) { + const encrypted = encryptBlockFn(ivBlock, key); + const block = data.slice(i, i + BLOCK_SIZE); + while (block.length < BLOCK_SIZE) block.push(0); + ivBlock = xorBlocks(encrypted, block); + cipherText.push(...ivBlock); + } + return cipherText.slice(0, messageLength); + } + + case "OFB": { + let ivBlock = [...iv]; + for (let i = 0; i < data.length; i += BLOCK_SIZE) { + ivBlock = encryptBlockFn(ivBlock, key); + const block = data.slice(i, i + BLOCK_SIZE); + while (block.length < BLOCK_SIZE) block.push(0); + cipherText.push(...xorBlocks(ivBlock, block)); + } + return cipherText.slice(0, messageLength); + } + + case "CTR": { + let counter = [...iv]; + for (let i = 0; i < data.length; i += BLOCK_SIZE) { + const encrypted = encryptBlockFn(counter, key); + const block = data.slice(i, i + BLOCK_SIZE); + while (block.length < BLOCK_SIZE) block.push(0); + cipherText.push(...xorBlocks(encrypted, block)); + counter = incrementCounter(counter); + } + return cipherText.slice(0, messageLength); + } + + default: + throw new OperationError(`Invalid block cipher mode: ${mode}`); + } + + return cipherText; +} + +/** + * Decrypt with block cipher modes + * + * @param {number[]} cipherText - Ciphertext bytes + * @param {number[]} key - 16-byte key + * @param {number[]} iv - 8-byte IV (ignored for ECB) + * @param {string} mode - "ECB", "CBC", "CFB", "OFB", "CTR" + * @param {string} padding - "PKCS5", "NO", "ZERO", "RANDOM", "BIT" + * @param {Function} encryptBlockFn - Block encrypt function (used for stream modes) + * @param {Function} decryptBlockFn - Block decrypt function (used for ECB/CBC) + * @returns {number[]} - Plaintext bytes + */ +function decryptWithMode(cipherText, key, iv, mode, padding, encryptBlockFn, decryptBlockFn) { + const originalLength = cipherText.length; + if (originalLength === 0) return []; + + if (mode === "ECB" || mode === "CBC") { + if ((originalLength % BLOCK_SIZE) !== 0) + throw new OperationError( + `Invalid ciphertext length: ${originalLength} bytes. Must be a multiple of ${BLOCK_SIZE}.` + ); + } else { + while ((cipherText.length % BLOCK_SIZE) !== 0) + cipherText.push(0); + } + + const plainText = []; + + switch (mode) { + case "ECB": + for (let i = 0; i < cipherText.length; i += BLOCK_SIZE) { + plainText.push(...decryptBlockFn(cipherText.slice(i, i + BLOCK_SIZE), key)); + } + break; + + case "CBC": { + let ivBlock = [...iv]; + for (let i = 0; i < cipherText.length; i += BLOCK_SIZE) { + const block = cipherText.slice(i, i + BLOCK_SIZE); + const decrypted = decryptBlockFn(block, key); + plainText.push(...xorBlocks(decrypted, ivBlock)); + ivBlock = block; + } + break; + } + + case "CFB": { + let ivBlock = [...iv]; + for (let i = 0; i < cipherText.length; i += BLOCK_SIZE) { + const encrypted = encryptBlockFn(ivBlock, key); + const block = cipherText.slice(i, i + BLOCK_SIZE); + plainText.push(...xorBlocks(encrypted, block)); + ivBlock = block; + } + return plainText.slice(0, originalLength); + } + + case "OFB": { + let ivBlock = [...iv]; + for (let i = 0; i < cipherText.length; i += BLOCK_SIZE) { + ivBlock = encryptBlockFn(ivBlock, key); + const block = cipherText.slice(i, i + BLOCK_SIZE); + plainText.push(...xorBlocks(ivBlock, block)); + } + return plainText.slice(0, originalLength); + } + + case "CTR": { + let counter = [...iv]; + for (let i = 0; i < cipherText.length; i += BLOCK_SIZE) { + const encrypted = encryptBlockFn(counter, key); + const block = cipherText.slice(i, i + BLOCK_SIZE); + plainText.push(...xorBlocks(encrypted, block)); + counter = incrementCounter(counter); + } + return plainText.slice(0, originalLength); + } + + default: + throw new OperationError(`Invalid block cipher mode: ${mode}`); + } + + if (mode === "ECB" || mode === "CBC") { + return removePadding(plainText, padding); + } + + return plainText.slice(0, originalLength); +} + + +// ==================== PUBLIC API ==================== + +/** + * Encrypt using TEA cipher + * @param {number[]} message - Plaintext bytes + * @param {number[]} key - 16-byte key + * @param {number[]} iv - 8-byte IV + * @param {string} mode - Block cipher mode + * @param {string} padding - Padding type + * @returns {number[]} - Ciphertext bytes + */ +export function encryptTEA(message, key, iv, mode = "ECB", padding = "PKCS5") { + return encryptWithMode(message, key, iv, mode, padding, teaEncryptBlock); +} + +/** + * Decrypt using TEA cipher + * @param {number[]} cipherText - Ciphertext bytes + * @param {number[]} key - 16-byte key + * @param {number[]} iv - 8-byte IV + * @param {string} mode - Block cipher mode + * @param {string} padding - Padding type + * @returns {number[]} - Plaintext bytes + */ +export function decryptTEA(cipherText, key, iv, mode = "ECB", padding = "PKCS5") { + return decryptWithMode(cipherText, key, iv, mode, padding, teaEncryptBlock, teaDecryptBlock); +} + +/** + * Encrypt using XTEA cipher + * @param {number[]} message - Plaintext bytes + * @param {number[]} key - 16-byte key + * @param {number[]} iv - 8-byte IV + * @param {string} mode - Block cipher mode + * @param {string} padding - Padding type + * @param {number} rounds - Number of rounds (default 32) + * @returns {number[]} - Ciphertext bytes + */ +export function encryptXTEA(message, key, iv, mode = "ECB", padding = "PKCS5", rounds = 32) { + const encFn = (block, k) => xteaEncryptBlock(block, k, rounds); + return encryptWithMode(message, key, iv, mode, padding, encFn); +} + +/** + * Decrypt using XTEA cipher + * @param {number[]} cipherText - Ciphertext bytes + * @param {number[]} key - 16-byte key + * @param {number[]} iv - 8-byte IV + * @param {string} mode - Block cipher mode + * @param {string} padding - Padding type + * @param {number} rounds - Number of rounds (default 32) + * @returns {number[]} - Plaintext bytes + */ +export function decryptXTEA(cipherText, key, iv, mode = "ECB", padding = "PKCS5", rounds = 32) { + const encFn = (block, k) => xteaEncryptBlock(block, k, rounds); + const decFn = (block, k) => xteaDecryptBlock(block, k, rounds); + return decryptWithMode(cipherText, key, iv, mode, padding, encFn, decFn); +} + +/** Block size in bytes (exported for operation validation) */ +export const TEA_BLOCK_SIZE = BLOCK_SIZE; diff --git a/src/core/operations/TEADecrypt.mjs b/src/core/operations/TEADecrypt.mjs new file mode 100644 index 0000000000..ab0a634b2a --- /dev/null +++ b/src/core/operations/TEADecrypt.mjs @@ -0,0 +1,98 @@ +/** + * @author Medjedtxm + * @copyright Crown Copyright 2026 + * @license Apache-2.0 + */ + +import Operation from "../Operation.mjs"; +import Utils from "../Utils.mjs"; +import OperationError from "../errors/OperationError.mjs"; +import { toHex } from "../lib/Hex.mjs"; +import { decryptTEA, TEA_BLOCK_SIZE } from "../lib/TEA.mjs"; + +/** + * TEA Decrypt operation + */ +class TEADecrypt extends Operation { + + /** + * TEADecrypt constructor + */ + constructor() { + super(); + + this.name = "TEA Decrypt"; + this.module = "Ciphers"; + this.description = "TEA (Tiny Encryption Algorithm) is a block cipher designed by David Wheeler and Roger Needham in 1994. It operates on 64-bit blocks using a 128-bit key and performs 32 cycles (64 Feistel rounds) with the DELTA constant 0x9E3779B9 derived from the golden ratio.

TEA is notable for its simplicity and compact implementation, making it frequently encountered in malware analysis and CTF challenges. Despite its elegance, TEA has known weaknesses including equivalent keys and susceptibility to related-key attacks, leading to successors XTEA and XXTEA.

Key: Must be exactly 16 bytes (128 bits).

IV: The Initialisation Vector should be 8 bytes (64 bits). If not entered, it will default to null bytes.

Padding: In CBC and ECB mode, the PKCS#5 padding scheme is used."; + this.infoURL = "https://wikipedia.org/wiki/Tiny_Encryption_Algorithm"; + this.inputType = "string"; + this.outputType = "string"; + this.args = [ + { + "name": "Key", + "type": "toggleString", + "value": "", + "toggleValues": ["Hex", "UTF8", "Latin1", "Base64"] + }, + { + "name": "IV", + "type": "toggleString", + "value": "", + "toggleValues": ["Hex", "UTF8", "Latin1", "Base64"] + }, + { + "name": "Mode", + "type": "option", + "value": ["CBC", "CFB", "OFB", "CTR", "ECB"] + }, + { + "name": "Input", + "type": "option", + "value": ["Hex", "Raw"] + }, + { + "name": "Output", + "type": "option", + "value": ["Raw", "Hex"] + }, + { + "name": "Padding", + "type": "option", + "value": ["PKCS5", "NO", "ZERO", "RANDOM", "BIT"] + } + ]; + } + + /** + * @param {string} input + * @param {Object[]} args + * @returns {string} + */ + run(input, args) { + const key = Utils.convertToByteArray(args[0].string, args[0].option), + iv = Utils.convertToByteArray(args[1].string, args[1].option), + [,, mode, inputType, outputType, padding] = args; + + if (key.length !== 16) + throw new OperationError(`Invalid key length: ${key.length} bytes + +TEA requires a key length of 16 bytes (128 bits). +Make sure you have specified the type correctly (e.g. Hex vs UTF8).`); + + if (iv.length !== TEA_BLOCK_SIZE && iv.length !== 0 && mode !== "ECB") + throw new OperationError(`Invalid IV length: ${iv.length} bytes + +TEA uses an IV length of ${TEA_BLOCK_SIZE} bytes (${TEA_BLOCK_SIZE * 8} bits). +Make sure you have specified the type correctly (e.g. Hex vs UTF8).`); + + // Default IV to null bytes if empty (like AES) + const actualIv = iv.length === 0 ? new Array(TEA_BLOCK_SIZE).fill(0) : iv; + + input = Utils.convertToByteArray(input, inputType); + const output = decryptTEA(input, key, actualIv, mode, padding); + return outputType === "Hex" ? toHex(output, "") : Utils.byteArrayToUtf8(output); + } + +} + +export default TEADecrypt; diff --git a/src/core/operations/TEAEncrypt.mjs b/src/core/operations/TEAEncrypt.mjs new file mode 100644 index 0000000000..c3f175dd90 --- /dev/null +++ b/src/core/operations/TEAEncrypt.mjs @@ -0,0 +1,98 @@ +/** + * @author Medjedtxm + * @copyright Crown Copyright 2026 + * @license Apache-2.0 + */ + +import Operation from "../Operation.mjs"; +import Utils from "../Utils.mjs"; +import OperationError from "../errors/OperationError.mjs"; +import { toHex } from "../lib/Hex.mjs"; +import { encryptTEA, TEA_BLOCK_SIZE } from "../lib/TEA.mjs"; + +/** + * TEA Encrypt operation + */ +class TEAEncrypt extends Operation { + + /** + * TEAEncrypt constructor + */ + constructor() { + super(); + + this.name = "TEA Encrypt"; + this.module = "Ciphers"; + this.description = "TEA (Tiny Encryption Algorithm) is a block cipher designed by David Wheeler and Roger Needham in 1994. It operates on 64-bit blocks using a 128-bit key and performs 32 cycles (64 Feistel rounds) with the DELTA constant 0x9E3779B9 derived from the golden ratio.

TEA is notable for its simplicity and compact implementation, making it frequently encountered in malware analysis and CTF challenges. Despite its elegance, TEA has known weaknesses including equivalent keys and susceptibility to related-key attacks, leading to successors XTEA and XXTEA.

Key: Must be exactly 16 bytes (128 bits).

IV: The Initialisation Vector should be 8 bytes (64 bits). If not entered, it will default to null bytes.

Padding: In CBC and ECB mode, the PKCS#5 padding scheme is used."; + this.infoURL = "https://wikipedia.org/wiki/Tiny_Encryption_Algorithm"; + this.inputType = "string"; + this.outputType = "string"; + this.args = [ + { + "name": "Key", + "type": "toggleString", + "value": "", + "toggleValues": ["Hex", "UTF8", "Latin1", "Base64"] + }, + { + "name": "IV", + "type": "toggleString", + "value": "", + "toggleValues": ["Hex", "UTF8", "Latin1", "Base64"] + }, + { + "name": "Mode", + "type": "option", + "value": ["CBC", "CFB", "OFB", "CTR", "ECB"] + }, + { + "name": "Input", + "type": "option", + "value": ["Raw", "Hex"] + }, + { + "name": "Output", + "type": "option", + "value": ["Hex", "Raw"] + }, + { + "name": "Padding", + "type": "option", + "value": ["PKCS5", "NO", "ZERO", "RANDOM", "BIT"] + } + ]; + } + + /** + * @param {string} input + * @param {Object[]} args + * @returns {string} + */ + run(input, args) { + const key = Utils.convertToByteArray(args[0].string, args[0].option), + iv = Utils.convertToByteArray(args[1].string, args[1].option), + [,, mode, inputType, outputType, padding] = args; + + if (key.length !== 16) + throw new OperationError(`Invalid key length: ${key.length} bytes + +TEA requires a key length of 16 bytes (128 bits). +Make sure you have specified the type correctly (e.g. Hex vs UTF8).`); + + if (iv.length !== TEA_BLOCK_SIZE && iv.length !== 0 && mode !== "ECB") + throw new OperationError(`Invalid IV length: ${iv.length} bytes + +TEA uses an IV length of ${TEA_BLOCK_SIZE} bytes (${TEA_BLOCK_SIZE * 8} bits). +Make sure you have specified the type correctly (e.g. Hex vs UTF8).`); + + // Default IV to null bytes if empty (like AES) + const actualIv = iv.length === 0 ? new Array(TEA_BLOCK_SIZE).fill(0) : iv; + + input = Utils.convertToByteArray(input, inputType); + const output = encryptTEA(input, key, actualIv, mode, padding); + return outputType === "Hex" ? toHex(output, "") : Utils.byteArrayToUtf8(output); + } + +} + +export default TEAEncrypt; diff --git a/src/core/operations/XTEADecrypt.mjs b/src/core/operations/XTEADecrypt.mjs new file mode 100644 index 0000000000..e3b6560b5f --- /dev/null +++ b/src/core/operations/XTEADecrypt.mjs @@ -0,0 +1,110 @@ +/** + * @author Medjedtxm + * @copyright Crown Copyright 2026 + * @license Apache-2.0 + */ + +import Operation from "../Operation.mjs"; +import Utils from "../Utils.mjs"; +import OperationError from "../errors/OperationError.mjs"; +import { toHex } from "../lib/Hex.mjs"; +import { decryptXTEA, TEA_BLOCK_SIZE } from "../lib/TEA.mjs"; + +/** + * XTEA Decrypt operation + */ +class XTEADecrypt extends Operation { + + /** + * XTEADecrypt constructor + */ + constructor() { + super(); + + this.name = "XTEA Decrypt"; + this.module = "Ciphers"; + this.description = "XTEA (eXtended Tiny Encryption Algorithm) is a block cipher designed by David Wheeler and Roger Needham in 1997 as a successor to TEA, correcting several weaknesses identified in the original algorithm. It operates on 64-bit blocks using a 128-bit key with an improved key schedule that uses sum-dependent key word selection to resist related-key attacks.

XTEA retains the simplicity and compact implementation of TEA whilst providing significantly improved security. It is frequently encountered in malware analysis and CTF challenges due to its straightforward implementation.

Key: Must be exactly 16 bytes (128 bits).

IV: The Initialisation Vector should be 8 bytes (64 bits). If not entered, it will default to null bytes.

Rounds: The recommended number of rounds is 32 (default). The reference implementation by Wheeler & Needham accepts a configurable round count.

Padding: In CBC and ECB mode, the PKCS#5 padding scheme is used."; + this.infoURL = "https://wikipedia.org/wiki/XTEA"; + this.inputType = "string"; + this.outputType = "string"; + this.args = [ + { + "name": "Key", + "type": "toggleString", + "value": "", + "toggleValues": ["Hex", "UTF8", "Latin1", "Base64"] + }, + { + "name": "IV", + "type": "toggleString", + "value": "", + "toggleValues": ["Hex", "UTF8", "Latin1", "Base64"] + }, + { + "name": "Mode", + "type": "option", + "value": ["CBC", "CFB", "OFB", "CTR", "ECB"] + }, + { + "name": "Input", + "type": "option", + "value": ["Hex", "Raw"] + }, + { + "name": "Output", + "type": "option", + "value": ["Raw", "Hex"] + }, + { + "name": "Padding", + "type": "option", + "value": ["PKCS5", "NO", "ZERO", "RANDOM", "BIT"] + }, + { + "name": "Rounds", + "type": "number", + "value": 32, + "min": 1, + "max": 255 + } + ]; + } + + /** + * @param {string} input + * @param {Object[]} args + * @returns {string} + */ + run(input, args) { + const key = Utils.convertToByteArray(args[0].string, args[0].option), + iv = Utils.convertToByteArray(args[1].string, args[1].option), + [,, mode, inputType, outputType, padding, rounds] = args; + + if (key.length !== 16) + throw new OperationError(`Invalid key length: ${key.length} bytes + +XTEA requires a key length of 16 bytes (128 bits). +Make sure you have specified the type correctly (e.g. Hex vs UTF8).`); + + if (iv.length !== TEA_BLOCK_SIZE && iv.length !== 0 && mode !== "ECB") + throw new OperationError(`Invalid IV length: ${iv.length} bytes + +XTEA uses an IV length of ${TEA_BLOCK_SIZE} bytes (${TEA_BLOCK_SIZE * 8} bits). +Make sure you have specified the type correctly (e.g. Hex vs UTF8).`); + + if (!Number.isInteger(rounds) || rounds < 1 || rounds > 255) + throw new OperationError(`Invalid number of rounds: ${rounds} + +Rounds must be an integer between 1 and 255. Standard XTEA uses 32 rounds.`); + + // Default IV to null bytes if empty (like AES) + const actualIv = iv.length === 0 ? new Array(TEA_BLOCK_SIZE).fill(0) : iv; + + input = Utils.convertToByteArray(input, inputType); + const output = decryptXTEA(input, key, actualIv, mode, padding, rounds); + return outputType === "Hex" ? toHex(output, "") : Utils.byteArrayToUtf8(output); + } + +} + +export default XTEADecrypt; diff --git a/src/core/operations/XTEAEncrypt.mjs b/src/core/operations/XTEAEncrypt.mjs new file mode 100644 index 0000000000..7d4bc1c166 --- /dev/null +++ b/src/core/operations/XTEAEncrypt.mjs @@ -0,0 +1,110 @@ +/** + * @author Medjedtxm + * @copyright Crown Copyright 2026 + * @license Apache-2.0 + */ + +import Operation from "../Operation.mjs"; +import Utils from "../Utils.mjs"; +import OperationError from "../errors/OperationError.mjs"; +import { toHex } from "../lib/Hex.mjs"; +import { encryptXTEA, TEA_BLOCK_SIZE } from "../lib/TEA.mjs"; + +/** + * XTEA Encrypt operation + */ +class XTEAEncrypt extends Operation { + + /** + * XTEAEncrypt constructor + */ + constructor() { + super(); + + this.name = "XTEA Encrypt"; + this.module = "Ciphers"; + this.description = "XTEA (eXtended Tiny Encryption Algorithm) is a block cipher designed by David Wheeler and Roger Needham in 1997 as a successor to TEA, correcting several weaknesses identified in the original algorithm. It operates on 64-bit blocks using a 128-bit key with an improved key schedule that uses sum-dependent key word selection to resist related-key attacks.

XTEA retains the simplicity and compact implementation of TEA whilst providing significantly improved security. It is frequently encountered in malware analysis and CTF challenges due to its straightforward implementation.

Key: Must be exactly 16 bytes (128 bits).

IV: The Initialisation Vector should be 8 bytes (64 bits). If not entered, it will default to null bytes.

Rounds: The recommended number of rounds is 32 (default). The reference implementation by Wheeler & Needham accepts a configurable round count.

Padding: In CBC and ECB mode, the PKCS#5 padding scheme is used."; + this.infoURL = "https://wikipedia.org/wiki/XTEA"; + this.inputType = "string"; + this.outputType = "string"; + this.args = [ + { + "name": "Key", + "type": "toggleString", + "value": "", + "toggleValues": ["Hex", "UTF8", "Latin1", "Base64"] + }, + { + "name": "IV", + "type": "toggleString", + "value": "", + "toggleValues": ["Hex", "UTF8", "Latin1", "Base64"] + }, + { + "name": "Mode", + "type": "option", + "value": ["CBC", "CFB", "OFB", "CTR", "ECB"] + }, + { + "name": "Input", + "type": "option", + "value": ["Raw", "Hex"] + }, + { + "name": "Output", + "type": "option", + "value": ["Hex", "Raw"] + }, + { + "name": "Padding", + "type": "option", + "value": ["PKCS5", "NO", "ZERO", "RANDOM", "BIT"] + }, + { + "name": "Rounds", + "type": "number", + "value": 32, + "min": 1, + "max": 255 + } + ]; + } + + /** + * @param {string} input + * @param {Object[]} args + * @returns {string} + */ + run(input, args) { + const key = Utils.convertToByteArray(args[0].string, args[0].option), + iv = Utils.convertToByteArray(args[1].string, args[1].option), + [,, mode, inputType, outputType, padding, rounds] = args; + + if (key.length !== 16) + throw new OperationError(`Invalid key length: ${key.length} bytes + +XTEA requires a key length of 16 bytes (128 bits). +Make sure you have specified the type correctly (e.g. Hex vs UTF8).`); + + if (iv.length !== TEA_BLOCK_SIZE && iv.length !== 0 && mode !== "ECB") + throw new OperationError(`Invalid IV length: ${iv.length} bytes + +XTEA uses an IV length of ${TEA_BLOCK_SIZE} bytes (${TEA_BLOCK_SIZE * 8} bits). +Make sure you have specified the type correctly (e.g. Hex vs UTF8).`); + + if (!Number.isInteger(rounds) || rounds < 1 || rounds > 255) + throw new OperationError(`Invalid number of rounds: ${rounds} + +Rounds must be an integer between 1 and 255. Standard XTEA uses 32 rounds.`); + + // Default IV to null bytes if empty (like AES) + const actualIv = iv.length === 0 ? new Array(TEA_BLOCK_SIZE).fill(0) : iv; + + input = Utils.convertToByteArray(input, inputType); + const output = encryptXTEA(input, key, actualIv, mode, padding, rounds); + return outputType === "Hex" ? toHex(output, "") : Utils.byteArrayToUtf8(output); + } + +} + +export default XTEAEncrypt; diff --git a/tests/operations/tests/TEA.mjs b/tests/operations/tests/TEA.mjs new file mode 100644 index 0000000000..aa1043fe69 --- /dev/null +++ b/tests/operations/tests/TEA.mjs @@ -0,0 +1,566 @@ +/** + * TEA and XTEA cipher tests. + * + * Test vectors sourced from: + * - TEA: https://www.cix.co.uk/~klockstone/teavect.htm (Wheeler & Needham reference) + * - XTEA: https://github.com/golang/crypto/blob/master/xtea/xtea_test.go (Go standard library) + * Bouncy Castle XTEA test vectors (big-endian) + * + * @author Medjedtxm + * @copyright Crown Copyright 2026 + * @license Apache-2.0 + */ + +import TestRegister from "../../lib/TestRegister.mjs"; + +/** + * TEA ECB Tests — Official test vectors from Wheeler & Needham + * + * From teavect.htm: TEA uses a fixed 32 cycles (64 Feistel rounds). + * Row 1: plaintext 00000000 00000000, key 00000000 00000000 00000000 00000000 + * -> ciphertext 41ea3a0a 94baa940 + */ +TestRegister.addTests([ + // ==================== TEA ECB TESTS ==================== + { + name: "TEA Encrypt: ECB, all-zero key and plaintext", + input: "0000000000000000", + expectedOutput: "41ea3a0a94baa940", + recipeConfig: [ + { + "op": "TEA Encrypt", + "args": [ + {"option": "Hex", "string": "00000000000000000000000000000000"}, + {"option": "Hex", "string": ""}, + "ECB", "Hex", "Hex", "NO" + ] + } + ], + }, + { + name: "TEA Decrypt: ECB, all-zero key", + input: "41ea3a0a94baa940", + expectedOutput: "0000000000000000", + recipeConfig: [ + { + "op": "TEA Decrypt", + "args": [ + {"option": "Hex", "string": "00000000000000000000000000000000"}, + {"option": "Hex", "string": ""}, + "ECB", "Hex", "Hex", "NO" + ] + } + ], + }, + { + name: "TEA Encrypt then Decrypt: round-trip ECB", + input: "48656c6c6f212121", + expectedOutput: "48656c6c6f212121", + recipeConfig: [ + { + "op": "TEA Encrypt", + "args": [ + {"option": "Hex", "string": "0123456789abcdef0123456789abcdef"}, + {"option": "Hex", "string": ""}, + "ECB", "Hex", "Hex", "NO" + ] + }, + { + "op": "TEA Decrypt", + "args": [ + {"option": "Hex", "string": "0123456789abcdef0123456789abcdef"}, + {"option": "Hex", "string": ""}, + "ECB", "Hex", "Hex", "NO" + ] + } + ], + }, + + // ==================== TEA CBC TEST ==================== + { + name: "TEA Encrypt then Decrypt: round-trip CBC with PKCS5", + input: "Hello TEA cipher!", + expectedOutput: "Hello TEA cipher!", + recipeConfig: [ + { + "op": "TEA Encrypt", + "args": [ + {"option": "Hex", "string": "0123456789abcdef0123456789abcdef"}, + {"option": "Hex", "string": "0000000000000000"}, + "CBC", "Raw", "Hex", "PKCS5" + ] + }, + { + "op": "TEA Decrypt", + "args": [ + {"option": "Hex", "string": "0123456789abcdef0123456789abcdef"}, + {"option": "Hex", "string": "0000000000000000"}, + "CBC", "Hex", "Raw", "PKCS5" + ] + } + ], + }, + + // ==================== TEA CTR TEST ==================== + { + name: "TEA Encrypt then Decrypt: round-trip CTR", + input: "Short", + expectedOutput: "Short", + recipeConfig: [ + { + "op": "TEA Encrypt", + "args": [ + {"option": "Hex", "string": "deadbeefdeadbeefdeadbeefdeadbeef"}, + {"option": "Hex", "string": "0102030405060708"}, + "CTR", "Raw", "Hex", "NO" + ] + }, + { + "op": "TEA Decrypt", + "args": [ + {"option": "Hex", "string": "deadbeefdeadbeefdeadbeefdeadbeef"}, + {"option": "Hex", "string": "0102030405060708"}, + "CTR", "Hex", "Raw", "NO" + ] + } + ], + }, + + // ==================== TEA CFB TEST ==================== + { + name: "TEA Encrypt then Decrypt: round-trip CFB", + input: "CFB mode testing with TEA", + expectedOutput: "CFB mode testing with TEA", + recipeConfig: [ + { + "op": "TEA Encrypt", + "args": [ + {"option": "Hex", "string": "0123456789abcdef0123456789abcdef"}, + {"option": "Hex", "string": "aabbccddeeff0011"}, + "CFB", "Raw", "Hex", "NO" + ] + }, + { + "op": "TEA Decrypt", + "args": [ + {"option": "Hex", "string": "0123456789abcdef0123456789abcdef"}, + {"option": "Hex", "string": "aabbccddeeff0011"}, + "CFB", "Hex", "Raw", "NO" + ] + } + ], + }, + + // ==================== TEA OFB TEST ==================== + { + name: "TEA Encrypt then Decrypt: round-trip OFB", + input: "OFB mode testing with TEA", + expectedOutput: "OFB mode testing with TEA", + recipeConfig: [ + { + "op": "TEA Encrypt", + "args": [ + {"option": "Hex", "string": "0123456789abcdef0123456789abcdef"}, + {"option": "Hex", "string": "1122334455667788"}, + "OFB", "Raw", "Hex", "NO" + ] + }, + { + "op": "TEA Decrypt", + "args": [ + {"option": "Hex", "string": "0123456789abcdef0123456789abcdef"}, + {"option": "Hex", "string": "1122334455667788"}, + "OFB", "Hex", "Raw", "NO" + ] + } + ], + }, + + // ==================== XTEA ECB TESTS ==================== + // Go standard library + Bouncy Castle test vectors (big-endian) + { + name: "XTEA Encrypt: ECB, sequential key, 'ABCDEFGH'", + input: "4142434445464748", + expectedOutput: "497df3d072612cb5", + recipeConfig: [ + { + "op": "XTEA Encrypt", + "args": [ + {"option": "Hex", "string": "000102030405060708090a0b0c0d0e0f"}, + {"option": "Hex", "string": ""}, + "ECB", "Hex", "Hex", "NO", 32 + ] + } + ], + }, + { + name: "XTEA Decrypt: ECB, sequential key", + input: "497df3d072612cb5", + expectedOutput: "4142434445464748", + recipeConfig: [ + { + "op": "XTEA Decrypt", + "args": [ + {"option": "Hex", "string": "000102030405060708090a0b0c0d0e0f"}, + {"option": "Hex", "string": ""}, + "ECB", "Hex", "Hex", "NO", 32 + ] + } + ], + }, + { + name: "XTEA Encrypt: ECB, sequential key, 'AAAAAAAA'", + input: "4141414141414141", + expectedOutput: "e78f2d13744341d8", + recipeConfig: [ + { + "op": "XTEA Encrypt", + "args": [ + {"option": "Hex", "string": "000102030405060708090a0b0c0d0e0f"}, + {"option": "Hex", "string": ""}, + "ECB", "Hex", "Hex", "NO", 32 + ] + } + ], + }, + { + name: "XTEA Encrypt: ECB, sequential key, plaintext 5a5b6e27", + input: "5a5b6e278948d77f", + expectedOutput: "4141414141414141", + recipeConfig: [ + { + "op": "XTEA Encrypt", + "args": [ + {"option": "Hex", "string": "000102030405060708090a0b0c0d0e0f"}, + {"option": "Hex", "string": ""}, + "ECB", "Hex", "Hex", "NO", 32 + ] + } + ], + }, + { + name: "XTEA Encrypt: ECB, all-zero key, 'ABCDEFGH'", + input: "4142434445464748", + expectedOutput: "a0390589f8b8efa5", + recipeConfig: [ + { + "op": "XTEA Encrypt", + "args": [ + {"option": "Hex", "string": "00000000000000000000000000000000"}, + {"option": "Hex", "string": ""}, + "ECB", "Hex", "Hex", "NO", 32 + ] + } + ], + }, + { + name: "XTEA Encrypt: ECB, all-zero key, 'AAAAAAAA'", + input: "4141414141414141", + expectedOutput: "ed23375a821a8c2d", + recipeConfig: [ + { + "op": "XTEA Encrypt", + "args": [ + {"option": "Hex", "string": "00000000000000000000000000000000"}, + {"option": "Hex", "string": ""}, + "ECB", "Hex", "Hex", "NO", 32 + ] + } + ], + }, + { + name: "XTEA Encrypt: ECB, all-zero key, all-zero plaintext", + input: "0000000000000000", + expectedOutput: "dee9d4d8f7131ed9", + recipeConfig: [ + { + "op": "XTEA Encrypt", + "args": [ + {"option": "Hex", "string": "00000000000000000000000000000000"}, + {"option": "Hex", "string": ""}, + "ECB", "Hex", "Hex", "NO", 32 + ] + } + ], + }, + { + name: "XTEA Encrypt: ECB, all-zero key, sequential plaintext", + input: "0102030405060708", + expectedOutput: "065c1b8975c6a816", + recipeConfig: [ + { + "op": "XTEA Encrypt", + "args": [ + {"option": "Hex", "string": "00000000000000000000000000000000"}, + {"option": "Hex", "string": ""}, + "ECB", "Hex", "Hex", "NO", 32 + ] + } + ], + }, + { + name: "XTEA Encrypt: ECB, pattern key, all-zero plaintext", + input: "0000000000000000", + expectedOutput: "1ff9a0261ac64264", + recipeConfig: [ + { + "op": "XTEA Encrypt", + "args": [ + {"option": "Hex", "string": "0123456712345678234567893456789a"}, + {"option": "Hex", "string": ""}, + "ECB", "Hex", "Hex", "NO", 32 + ] + } + ], + }, + { + name: "XTEA Encrypt: ECB, pattern key, sequential plaintext", + input: "0102030405060708", + expectedOutput: "8c67155b2ef91ead", + recipeConfig: [ + { + "op": "XTEA Encrypt", + "args": [ + {"option": "Hex", "string": "0123456712345678234567893456789a"}, + {"option": "Hex", "string": ""}, + "ECB", "Hex", "Hex", "NO", 32 + ] + } + ], + }, + { + name: "XTEA Decrypt: ECB, pattern key, sequential ciphertext", + input: "8c67155b2ef91ead", + expectedOutput: "0102030405060708", + recipeConfig: [ + { + "op": "XTEA Decrypt", + "args": [ + {"option": "Hex", "string": "0123456712345678234567893456789a"}, + {"option": "Hex", "string": ""}, + "ECB", "Hex", "Hex", "NO", 32 + ] + } + ], + }, + + // ==================== XTEA CBC TEST ==================== + { + name: "XTEA Encrypt then Decrypt: round-trip CBC with PKCS5", + input: "Hello XTEA cipher!", + expectedOutput: "Hello XTEA cipher!", + recipeConfig: [ + { + "op": "XTEA Encrypt", + "args": [ + {"option": "Hex", "string": "0123456789abcdef0123456789abcdef"}, + {"option": "Hex", "string": "fedcba9876543210"}, + "CBC", "Raw", "Hex", "PKCS5", 32 + ] + }, + { + "op": "XTEA Decrypt", + "args": [ + {"option": "Hex", "string": "0123456789abcdef0123456789abcdef"}, + {"option": "Hex", "string": "fedcba9876543210"}, + "CBC", "Hex", "Raw", "PKCS5", 32 + ] + } + ], + }, + + // ==================== XTEA OFB TEST ==================== + { + name: "XTEA Encrypt then Decrypt: round-trip OFB", + input: "Stream mode test", + expectedOutput: "Stream mode test", + recipeConfig: [ + { + "op": "XTEA Encrypt", + "args": [ + {"option": "Hex", "string": "deadbeefdeadbeefdeadbeefdeadbeef"}, + {"option": "Hex", "string": "0102030405060708"}, + "OFB", "Raw", "Hex", "NO", 32 + ] + }, + { + "op": "XTEA Decrypt", + "args": [ + {"option": "Hex", "string": "deadbeefdeadbeefdeadbeefdeadbeef"}, + {"option": "Hex", "string": "0102030405060708"}, + "OFB", "Hex", "Raw", "NO", 32 + ] + } + ], + }, + + // ==================== XTEA CTR TEST ==================== + { + name: "XTEA Encrypt then Decrypt: round-trip CTR", + input: "CTR mode with XTEA", + expectedOutput: "CTR mode with XTEA", + recipeConfig: [ + { + "op": "XTEA Encrypt", + "args": [ + {"option": "Hex", "string": "deadbeefdeadbeefdeadbeefdeadbeef"}, + {"option": "Hex", "string": "0000000000000001"}, + "CTR", "Raw", "Hex", "NO", 32 + ] + }, + { + "op": "XTEA Decrypt", + "args": [ + {"option": "Hex", "string": "deadbeefdeadbeefdeadbeefdeadbeef"}, + {"option": "Hex", "string": "0000000000000001"}, + "CTR", "Hex", "Raw", "NO", 32 + ] + } + ], + }, + + // ==================== XTEA CFB TEST ==================== + { + name: "XTEA Encrypt then Decrypt: round-trip CFB", + input: "CFB mode with XTEA cipher", + expectedOutput: "CFB mode with XTEA cipher", + recipeConfig: [ + { + "op": "XTEA Encrypt", + "args": [ + {"option": "Hex", "string": "0123456789abcdef0123456789abcdef"}, + {"option": "Hex", "string": "aabbccddeeff0011"}, + "CFB", "Raw", "Hex", "NO", 32 + ] + }, + { + "op": "XTEA Decrypt", + "args": [ + {"option": "Hex", "string": "0123456789abcdef0123456789abcdef"}, + {"option": "Hex", "string": "aabbccddeeff0011"}, + "CFB", "Hex", "Raw", "NO", 32 + ] + } + ], + }, + + // ==================== XTEA NON-DEFAULT ROUNDS TEST ==================== + { + name: "XTEA Encrypt then Decrypt: round-trip ECB with 16 rounds", + input: "4142434445464748", + expectedOutput: "4142434445464748", + recipeConfig: [ + { + "op": "XTEA Encrypt", + "args": [ + {"option": "Hex", "string": "000102030405060708090a0b0c0d0e0f"}, + {"option": "Hex", "string": ""}, + "ECB", "Hex", "Hex", "NO", 16 + ] + }, + { + "op": "XTEA Decrypt", + "args": [ + {"option": "Hex", "string": "000102030405060708090a0b0c0d0e0f"}, + {"option": "Hex", "string": ""}, + "ECB", "Hex", "Hex", "NO", 16 + ] + } + ], + }, + { + name: "XTEA Encrypt: ECB, 16 rounds differs from 32 rounds", + input: "4142434445464748", + expectedOutput: "497df3d072612cb5", + recipeConfig: [ + { + "op": "XTEA Encrypt", + "args": [ + {"option": "Hex", "string": "000102030405060708090a0b0c0d0e0f"}, + {"option": "Hex", "string": ""}, + "ECB", "Hex", "Hex", "NO", 32 + ] + } + ], + }, + + // ==================== EDGE CASES ==================== + { + name: "TEA Encrypt: empty input returns empty", + input: "", + expectedOutput: "", + recipeConfig: [ + { + "op": "TEA Encrypt", + "args": [ + {"option": "Hex", "string": "00000000000000000000000000000000"}, + {"option": "Hex", "string": ""}, + "ECB", "Hex", "Hex", "NO" + ] + } + ], + }, + { + name: "XTEA Encrypt: empty input returns empty", + input: "", + expectedOutput: "", + recipeConfig: [ + { + "op": "XTEA Encrypt", + "args": [ + {"option": "Hex", "string": "00000000000000000000000000000000"}, + {"option": "Hex", "string": ""}, + "ECB", "Hex", "Hex", "NO", 32 + ] + } + ], + }, + + // ==================== MULTI-BLOCK ECB TESTS ==================== + { + name: "TEA Encrypt then Decrypt: multi-block ECB with PKCS5", + input: "This is a longer message that spans multiple TEA blocks!", + expectedOutput: "This is a longer message that spans multiple TEA blocks!", + recipeConfig: [ + { + "op": "TEA Encrypt", + "args": [ + {"option": "Hex", "string": "0123456789abcdef0123456789abcdef"}, + {"option": "Hex", "string": ""}, + "ECB", "Raw", "Hex", "PKCS5" + ] + }, + { + "op": "TEA Decrypt", + "args": [ + {"option": "Hex", "string": "0123456789abcdef0123456789abcdef"}, + {"option": "Hex", "string": ""}, + "ECB", "Hex", "Raw", "PKCS5" + ] + } + ], + }, + { + name: "XTEA Encrypt then Decrypt: multi-block ECB with PKCS5", + input: "This is a longer message that spans multiple XTEA blocks!", + expectedOutput: "This is a longer message that spans multiple XTEA blocks!", + recipeConfig: [ + { + "op": "XTEA Encrypt", + "args": [ + {"option": "Hex", "string": "0123456789abcdef0123456789abcdef"}, + {"option": "Hex", "string": ""}, + "ECB", "Raw", "Hex", "PKCS5", 32 + ] + }, + { + "op": "XTEA Decrypt", + "args": [ + {"option": "Hex", "string": "0123456789abcdef0123456789abcdef"}, + {"option": "Hex", "string": ""}, + "ECB", "Hex", "Raw", "PKCS5", 32 + ] + } + ], + }, +]);