-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
74 lines (57 loc) · 1.91 KB
/
index.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//get buttons
const encryptButton = document.getElementById('encryptButton');
const decryptButton = document.getElementById('decryptButton');
//encrypt function
function encrypt() {
let inputText = document.getElementById('input').value;
console.log(inputText);
let key = document.getElementById('key').value;
//check if key is a number
if (!/^\d+$/.test(key)) {
alert("Key must only contain numeric characters!");
return;}
let encryptedText = '';
let resultArr = [];
let keyStr = key.toString();
let keyArr = keyStr.split("").map(Number);
let j = 0;
for (let i = 0; i < inputText.length; i++) {
let charCode = inputText.charCodeAt(i);
resultArr.push(charCode - keyArr[j]);
j = (j+1) % keyArr.length;
} return String.fromCharCode(...resultArr);
}
//decrypt function
function decrypt() {
let inputText = document.getElementById('input').value;
console.log(inputText);
let key = document.getElementById('key').value;
//check if key is a number
if (!/^\d+$/.test(key)) {
alert("Key must only contain numeric characters!");
return;}
let decryptedText = '';
let resultArr = [];
let keyStr = key.toString();
let keyArr = keyStr.split("").map(Number);
let j = 0;
for (let i = 0; i < inputText.length; i++) {
let charCode = inputText.charCodeAt(i);
resultArr.push(charCode + keyArr[j]);
j = (j+1) % keyArr.length;
} return String.fromCharCode(...resultArr);
}
//event listeners
encryptButton.addEventListener('click', () => {
console.log('encrypt button clicked');
const outputText = encrypt();
document.getElementById('output').innerHTML = outputText;
});
decryptButton.addEventListener('click', () => {
console.log('decrypt button clicked');
const outputText = decrypt();
document.getElementById('output').innerHTML = outputText;
});
document.getElementById('output').addEventListener('cut', (e) => {
e.preventDefault();
});