Make encryption based on pad instead of message

This commit is contained in:
Robbie Antenesse 2018-02-21 10:27:01 -07:00 committed by Robbie Antenesse
parent 0a543a4f33
commit 2642f2a251
1 changed files with 10 additions and 8 deletions

View File

@ -19,22 +19,24 @@ const stripString = (string) => {
} }
export const encrypt = (string, pad = null) => { export const encrypt = (string, pad = null) => {
const strippedString = stripString(string); const strippedString = stripString(string).toUpperCase();
pad = pad ? pad : generatePad(strippedString.length); pad = pad ? pad : generatePad(strippedString.length * 2);
return { return {
oneTimePad: pad, oneTimePad: pad,
encryptedMessage: strippedString.toUpperCase().split('').map((letter, index) => { encryptedMessage: pad.map((letter, index) => {
const letterValue = CHARS.indexOf(letter); const messageLetter = strippedString.charAt(index);
const padValue = CHARS.indexOf(pad[index]); const letterValue = messageLetter !== '' ? CHARS.indexOf(messageLetter) : CHARS.length - 1;
const padValue = CHARS.indexOf(letter);
return CHARS[(letterValue + padValue) % CHARS.length]; return CHARS[(letterValue + padValue) % CHARS.length];
}).join(''), }).join(''),
}; };
} }
export const decrypt = (string, pad) => { export const decrypt = (string, pad) => {
return string.split('').map((letter, index) => { string = string.toUpperCase();
const letterValue = CHARS.indexOf(letter); return pad.map((letter, index) => {
const padValue = CHARS.indexOf(pad[index]); const letterValue = CHARS.indexOf(string.charAt(index));
const padValue = CHARS.indexOf(letter);
let charIndex = (letterValue - padValue); let charIndex = (letterValue - padValue);
while (charIndex < 0) {charIndex += CHARS.length} while (charIndex < 0) {charIndex += CHARS.length}
return CHARS[charIndex % CHARS.length]; return CHARS[charIndex % CHARS.length];