|
| 1 | +/** |
| 2 | + * Substitution Cipher |
| 3 | + * |
| 4 | + * A monoalphabetic substitution cipher replaces each letter of the plaintext |
| 5 | + * with another letter based on a fixed permutation (key) of the alphabet. |
| 6 | + * https://en.wikipedia.org/wiki/Substitution_cipher |
| 7 | + */ |
| 8 | + |
| 9 | +const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' |
| 10 | +const defaultKey = 'QWERTYUIOPASDFGHJKLZXCVBNM' |
| 11 | + |
| 12 | +/** |
| 13 | + * Encrypts a string using a monoalphabetic substitution cipher |
| 14 | + * @param {string} text - The text to encrypt |
| 15 | + * @param {string} key - The substitution key (must be 26 uppercase letters) |
| 16 | + * @returns {string} |
| 17 | + */ |
| 18 | +export function substitutionCipherEncryption(text, key = defaultKey) { |
| 19 | + if (key.length !== 26 || !/^[A-Z]+$/.test(key)) { |
| 20 | + throw new RangeError('Key must be 26 uppercase English letters.') |
| 21 | + } |
| 22 | + |
| 23 | + let result = '' |
| 24 | + const textUpper = text.toUpperCase() |
| 25 | + for (let i = 0; i < textUpper.length; i++) { |
| 26 | + const char = textUpper[i] |
| 27 | + const index = alphabet.indexOf(char) |
| 28 | + if (index !== -1) { |
| 29 | + result += key[index] |
| 30 | + } else { |
| 31 | + result += char |
| 32 | + } |
| 33 | + } |
| 34 | + return result |
| 35 | +} |
| 36 | +/** |
| 37 | + * Decrypts a string encrypted with the substitution cipher |
| 38 | + * @param {string} text - The encrypted text |
| 39 | + * @param {string} key - The substitution key used during encryption |
| 40 | + * @returns {string} |
| 41 | + */ |
| 42 | +export function substitutionCipherDecryption(text, key = defaultKey) { |
| 43 | + if (key.length !== 26 || !/^[A-Z]+$/.test(key)) { |
| 44 | + throw new RangeError('Key must be 26 uppercase English letters.') |
| 45 | + } |
| 46 | + |
| 47 | + let result = '' |
| 48 | + const textUpper = text.toUpperCase() |
| 49 | + for (let i = 0; i < textUpper.length; i++) { |
| 50 | + const char = textUpper[i] |
| 51 | + const index = key.indexOf(char) |
| 52 | + if (index !== -1) { |
| 53 | + result += alphabet[index] |
| 54 | + } else { |
| 55 | + result += char |
| 56 | + } |
| 57 | + } |
| 58 | + return result |
| 59 | +} |
0 commit comments