Skip to content

Commit 94c0594

Browse files
authored
algorithm: xor cipher (TheAlgorithms#24)
1 parent 4411944 commit 94c0594

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

Ciphers/XORCipher.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
/**
2+
* @function XORCipher
3+
* @description - Encrypt using an XOR cipher
4+
* The XOR cipher is a type of additive cipher.
5+
* Each character is bitwise XORed with the key.
6+
* We loop through the input string, XORing each
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
11+
*/
12+
export const XORCipher = (str: string, key: number): string =>
13+
str.replace(/./g, (char: string) =>
14+
String.fromCharCode(char.charCodeAt(0) ^ key)
15+
)

Ciphers/test/XORCipher.test.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import { XORCipher } from '../XORCipher';
2+
3+
describe('Testing XORCipher function', () => {
4+
it('passing a string & number as an argument', () => {
5+
expect(XORCipher('test', 32)).toBe('TEST');
6+
expect(XORCipher('TEST', 32)).toBe('test');
7+
});
8+
});

0 commit comments

Comments
 (0)