From 4a4b18ed045e8eb6821e427200a8d87daad59685 Mon Sep 17 00:00:00 2001 From: Tharakadhanushka <55351120+Tharakadhanushka@users.noreply.github.com> Date: Sun, 15 Oct 2023 10:07:25 +0530 Subject: [PATCH] Create SubstitutionCipher.js SubstitutionCipher --- Ciphers/SubstitutionCipher.js | 45 +++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Ciphers/SubstitutionCipher.js diff --git a/Ciphers/SubstitutionCipher.js b/Ciphers/SubstitutionCipher.js new file mode 100644 index 0000000000..b98ac8cb51 --- /dev/null +++ b/Ciphers/SubstitutionCipher.js @@ -0,0 +1,45 @@ +function createCipher(key) { + const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; + const cipher = {}; + + for (let i = 0; i < alphabet.length; i++) { + cipher[alphabet[i]] = key[i] || alphabet[i]; + } + + return cipher; +} + +function encrypt(plainText, cipher) { + return plainText + .toUpperCase() // Convert to uppercase for consistency + .split('') + .map(char => cipher[char] || char) + .join(''); +} + +function decrypt(encryptedText, cipher) { + const reverseCipher = {}; + for (const key in cipher) { + if (cipher.hasOwnProperty(key)) { + reverseCipher[cipher[key]] = key; + } + } + + return encryptedText + .toUpperCase() + .split('') + .map(char => reverseCipher[char] || char) + .join(''); +} + +// Example usage: +const key = 'XZVTPONMLKJIHGFEDCBA'; +const text = 'Hello, World!'; + +const cipher = createCipher(key); +const encryptedText = encrypt(text, cipher); +const decryptedText = decrypt(encryptedText, cipher); + +console.log('Original text:', text); +console.log('Encrypted text:', encryptedText); +console.log('Decrypted text:', decryptedText);