From 4be7a85fd396caaaefba184925413508dfbdc62d Mon Sep 17 00:00:00 2001 From: LethargicLeprechaun <64550669+LethargicLeprechaun@users.noreply.github.com> Date: Tue, 23 Jun 2020 05:47:44 +0100 Subject: [PATCH] Added an XOR cipher (#135) * Added an XOR cipher * Rename xor_cipher.js to XORCipher.js * Update XORCipher.js Co-authored-by: vinayak --- Ciphers/XORCipher.js | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Ciphers/XORCipher.js diff --git a/Ciphers/XORCipher.js b/Ciphers/XORCipher.js new file mode 100644 index 000000000..898b200dd --- /dev/null +++ b/Ciphers/XORCipher.js @@ -0,0 +1,26 @@ +/** + * The XOR cipher is a type of additive cipher. + * Each character is bitwise XORed with the key. + * We loop through the input string, XORing each + * character with the key. + */ + +/** + * Encrypt using an XOR cipher + * @param {String} str - String to be encrypted + * @param {Number} key - key for encryption + * @return {String} encrypted string + */ + +function XOR (str, key) { + let result = '' + for (const elem of str) { + result += String.fromCharCode(elem.charCodeAt(0) ^ key) + } + return result +} + +const encryptedString = XOR('test string', 32) +console.log('Encrypted: ', encryptedString) +const decryptedString = XOR(encryptedString, 32) +console.log('Decrypted: ', decryptedString)