|
1 | 1 | /**
|
| 2 | + * @function XORCipher |
| 3 | + * @description - Encrypt using an XOR cipher |
2 | 4 | * The XOR cipher is a type of additive cipher.
|
3 | 5 | * Each character is bitwise XORed with the key.
|
4 | 6 | * We loop through the input string, XORing each
|
5 | 7 | * character with the key.
|
| 8 | + * @param {string} str - string to be encrypted |
| 9 | + * @param {number} key - key for encryption |
| 10 | + * @return {string} encrypted string |
6 | 11 | */
|
7 |
| - |
8 |
| -/** |
9 |
| - * Encrypt using an XOR cipher |
10 |
| - * @param {String} str - String to be encrypted |
11 |
| - * @param {Number} key - key for encryption |
12 |
| - * @return {String} encrypted string |
13 |
| - */ |
14 |
| - |
15 |
| -function XOR (str, key) { |
16 |
| - let result = '' |
17 |
| - for (const elem of str) { |
18 |
| - result += String.fromCharCode(elem.charCodeAt(0) ^ key) |
| 12 | +const XORCipher = (str, key) => { |
| 13 | + if (typeof str !== 'string' || !Number.isInteger(key)) { |
| 14 | + throw new TypeError('Arguments type are invalid') |
19 | 15 | }
|
20 |
| - return result |
21 |
| -} |
22 |
| - |
23 |
| -export { XOR } |
24 | 16 |
|
25 |
| -// Nb: Node REPL might not output the null char '\x00' (charcode 0) |
26 |
| - |
27 |
| -// > XOR('test string', 32) |
28 |
| -// 'TEST\x00STRING' |
| 17 | + return str.replace( |
| 18 | + /./g, (char) => String.fromCharCode(char.charCodeAt() ^ key) |
| 19 | + ) |
| 20 | +} |
29 | 21 |
|
30 |
| -// > XOR('TEST\x00STRING', 32) |
31 |
| -// 'test string' |
| 22 | +export default XORCipher |
0 commit comments