-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
53 lines (41 loc) · 1.73 KB
/
script.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
function handleEncrypt() {
const user_key = document.getElementById('key').value;
const user_data = document.getElementById('data').value;
if (user_key.length < 1) {
alert("Must enter a key to encrypt. Try again.")
}
else if (user_data.length < 1) {
alert("Must enter data to encrypt. Try again.")
}
else {
let encrypted_data = cipher(user_key, user_data);
document.getElementById('enc_data').innerHTML = encrypted_data;
document.getElementById('key').value = '';
document.getElementById('data').value = '';
}
}
function cipher(key, data) {
// convert the data and key into string first
key = key.toString()
data = data.toString()
// Declare the signature
const signature = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
let arr = []
//we'll get the key in format 4.34.0.39.
// convert the key into sets
let sets = key.split('.') // sets = [4,34,0,39]
for (let i = 0; i < sets.length; i++) {
if (i % 2 == 0) {
arr.push({ a: sets[i], b: sets[i + 1] })
}
}
// arr will be -> [{a:4,b:34}, {a:0,b:39}]
arr.forEach((elem) => {
let char1 = signature[elem.a]
let char2 = signature[elem.b]
let regex1 = new RegExp(char1, 'g')
let regex2 = new RegExp(char2, 'g')
data = data.replace(regex1, "!&").replace(regex2, char1).replace(/!&/g, char2) // we are using !& as temporary characters for swapping.
})
return data
}