diff --git a/Ciphers/XORCipher.js b/Ciphers/XORCipher.js index 944081b99..d73827a2e 100644 --- a/Ciphers/XORCipher.js +++ b/Ciphers/XORCipher.js @@ -1,31 +1,22 @@ /** + * @function XORCipher + * @description - Encrypt using an XOR cipher * 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. + * @param {string} str - string to be encrypted + * @param {number} key - key for encryption + * @return {string} encrypted string */ - -/** - * 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) +const XORCipher = (str, key) => { + if (typeof str !== 'string' || !Number.isInteger(key)) { + throw new TypeError('Arguments type are invalid') } - return result + + return str.replace( + /./g, (char) => String.fromCharCode(char.charCodeAt() ^ key) + ) } -export { XOR } - -// Nb: Node REPL might not output the null char '\x00' (charcode 0) - -// > XOR('test string', 32) -// 'TEST\x00STRING' - -// > XOR('TEST\x00STRING', 32) -// 'test string' +export default XORCipher diff --git a/Ciphers/test/XORCipher.test.js b/Ciphers/test/XORCipher.test.js new file mode 100644 index 000000000..9697fc715 --- /dev/null +++ b/Ciphers/test/XORCipher.test.js @@ -0,0 +1,18 @@ +import XORCipher from '../XORCipher' + +describe('Testing XORCipher function', () => { + it('Test - 1, passing a non-string as an argument', () => { + expect(() => XORCipher(false, 0x345)).toThrow() + expect(() => XORCipher(true, 123)).toThrow() + expect(() => XORCipher(1n, 123n)).toThrow() + expect(() => XORCipher(false, 0.34)).toThrow() + expect(() => XORCipher({})).toThrow() + expect(() => XORCipher([])).toThrow() + }) + + it('Test - 2, passing a string & number as an argument', () => { + // NB: Node REPL might not output the null char '\x00' (charcode 0) + expect(XORCipher('test string', 32)).toBe('TEST\x00STRING') + expect(XORCipher('TEST\x00STRING', 32)).toBe('test string') + }) +})