Allow creating custom pad as long as it's longer than the input.

This commit is contained in:
Robbie Antenesse 2018-02-20 23:27:01 -07:00
parent b660acac57
commit 0be7c788c3
2 changed files with 10 additions and 8 deletions

View File

@ -16,10 +16,10 @@
<body>
<strong>Your Message</strong><br>
<textarea id="input"></textarea><br>
<strong>One-Time Pad</strong><br>
<textarea id="inputPad"></textarea><br>
<button id="encryptInput">Encrypt</button><br>
<br>
<strong>One-Time Pad</strong><br>
<pre id="pad"></pre><br>
<strong>Encrypted Message</strong><br>
<pre id="encrypted"></pre><br>
<br>

View File

@ -5,18 +5,18 @@ const CHARS = [
'&', '$',
];
const generatePad = (string) => {
const generatePad = (length) => {
const pad = [];
for (let i = 0; i < string.length; i++) {
for (let i = 0; i < length; i++) {
const letter = Math.floor(Math.random() * CHARS.length);
pad.push(CHARS[letter]);
}
return pad;
}
export const encrypt = (string) => {
export const encrypt = (string, pad = null) => {
const strippedString = string.replace(/[\s]+/g, '&').replace(/[^a-zA-Z0-9\&]/g, '$');
const pad = generatePad(strippedString);
pad = pad ? pad : generatePad(strippedString.length);
return {
oneTimePad: pad,
encryptedMessage: strippedString.toUpperCase().split('').map((letter, index) => {
@ -39,8 +39,10 @@ export const decrypt = (string, pad) => {
document.getElementById('encryptInput').onclick = () => {
const input = document.getElementById('input').value;
const encryption = encrypt(input);
document.getElementById('pad').innerHTML = encryption.oneTimePad.join('');
const inputPad = document.getElementById('inputPad').value;
const pad = inputPad !== '' && inputPad.length >= input.length ? inputPad.split('') : null;
const encryption = encrypt(input, pad);
document.getElementById('inputPad').value = encryption.oneTimePad.join('');
document.getElementById('encrypted').innerHTML = encryption.encryptedMessage;
}