2018-02-21 06:09:02 +01:00
|
|
|
const CHARS = [
|
|
|
|
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
|
|
|
|
'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
|
2018-02-21 06:56:10 +01:00
|
|
|
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '$'
|
2018-02-21 06:09:02 +01:00
|
|
|
];
|
|
|
|
|
2018-02-21 06:55:29 +01:00
|
|
|
const generatePad = (string) => {
|
2018-02-21 06:09:02 +01:00
|
|
|
const pad = [];
|
|
|
|
for (let i = 0; i < string.length; i++) {
|
|
|
|
const letter = Math.floor(Math.random() * CHARS.length);
|
2018-02-21 06:53:33 +01:00
|
|
|
pad.push(CHARS[letter]);
|
2018-02-21 06:09:02 +01:00
|
|
|
}
|
|
|
|
return pad;
|
|
|
|
}
|
|
|
|
|
2018-02-21 06:55:29 +01:00
|
|
|
export const encrypt = (string) => {
|
2018-02-21 06:56:10 +01:00
|
|
|
const strippedString = string.replace(/[\s]+/g, '$').replace(/[^a-zA-Z0-9\$]/g, '');
|
2018-02-21 06:09:02 +01:00
|
|
|
const pad = generatePad(strippedString);
|
|
|
|
return {
|
|
|
|
oneTimePad: pad,
|
|
|
|
encryptedMessage: strippedString.toUpperCase().split('').map((letter, index) => {
|
|
|
|
const letterValue = CHARS.indexOf(letter);
|
|
|
|
const padValue = CHARS.indexOf(pad[index]);
|
|
|
|
return CHARS[(letterValue + padValue) % CHARS.length];
|
|
|
|
}).join(''),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2018-02-21 06:55:29 +01:00
|
|
|
export const decrypt = (string, pad) => {
|
2018-02-21 06:09:02 +01:00
|
|
|
return string.split('').map((letter, index) => {
|
|
|
|
const letterValue = CHARS.indexOf(letter);
|
|
|
|
const padValue = CHARS.indexOf(pad[index]);
|
2018-02-21 06:54:38 +01:00
|
|
|
let charIndex = (letterValue - padValue);
|
|
|
|
while (charIndex < 0) {charIndex += CHARS.length}
|
|
|
|
return CHARS[charIndex % CHARS.length];
|
2018-02-21 06:56:10 +01:00
|
|
|
}).join('').replace(/\$/g, ' ');
|
2018-02-21 06:09:02 +01:00
|
|
|
}
|
2018-02-21 06:53:33 +01:00
|
|
|
|
|
|
|
document.getElementById('encryptInput').onclick = () => {
|
|
|
|
const input = document.getElementById('input').value;
|
|
|
|
const encryption = encrypt(input);
|
|
|
|
document.getElementById('pad').innerHTML = encryption.oneTimePad.join('');
|
|
|
|
document.getElementById('encrypted').innerHTML = encryption.encryptedMessage;
|
|
|
|
}
|
|
|
|
|
|
|
|
document.getElementById('decryptInput').onclick = () => {
|
|
|
|
const input = document.getElementById('encryptedInput').value;
|
|
|
|
const pad = document.getElementById('encryptedInputPad').value.split('');
|
|
|
|
const output = decrypt(input, pad);
|
|
|
|
document.getElementById('decrypted').innerHTML = output;
|
|
|
|
}
|