-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy path15-cipher.js
43 lines (37 loc) · 1.3 KB
/
15-cipher.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
//
// Extract from https://stackoverflow.com/questions/18279141/javascript-string-encryption-and-decryption
// Contributed by https://stackoverflow.com/users/2861702/jorgeblom
//
/*
* Simplist symetric encoding using a shared secret
*
*/
const cipher = salt => {
const textToChars = text => text.split('').map(c => c.charCodeAt(0));
const byteHex = n => ("0" + Number(n).toString(16)).substr(-2);
const applySaltToChar = code => textToChars(salt).reduce((a,b) => a ^ b, code);
return text => text.split('')
.map(textToChars)
.map(applySaltToChar)
.map(byteHex)
.join('');
}
const decipher = salt => {
const textToChars = text => text.split('').map(c => c.charCodeAt(0));
const applySaltToChar = code => textToChars(salt).reduce((a,b) => a ^ b, code);
return encoded => encoded.match(/.{1,2}/g)
.map(hex => parseInt(hex, 16))
.map(applySaltToChar)
.map(charCode => String.fromCharCode(charCode))
.join('');
}
// Example
const text = 'Vision without execution is hallucination';
console.log(`BEFORE: ${text}`);
const encrypted = cipher('not so secret')(text);
console.log(`ENCRYPTED: ${encrypted}`);
const decrypted = decipher('not so secret')(encrypted);
console.log(`DECRYPTED: ${decrypted}`);
if (text !== decrypted) {
console.error('failed');
}