-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvigenere.js
53 lines (43 loc) · 1.52 KB
/
vigenere.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 VigenèreCipher(key, abc) {
const vigenereMatrix = [];
for ( let i = 0; i < key.length; i++ ) {
const row = [];
const shift = abc.indexOf(key[i]);
for (let j = 0; j < abc.length; j++) {
row.push(abc[(j + shift) % abc.length]);
}
vigenereMatrix.push(row);
}
this.encode = function (str) {
let result = '';
for (let k = 0; k < str.length; k++) {
if (abc.indexOf(str[k]) !== -1) {
const rowIndex = k % key.length;
const row = vigenereMatrix[rowIndex];
const colIndex = abc.indexOf(str[k]);
result += row[colIndex];
} else {
result += str[k];
}
}
return result;
};
this.decode = function (str) {
let result = '';
for (let index = 0; index < str.length; index++) {
if (abc.indexOf(str[index]) !== -1) {
const rowIndex = index % key.length;
const row = vigenereMatrix[rowIndex];
const colIndex = row.indexOf(str[index]);
result += abc[colIndex];
} else {
result += str[index];
}
}
return result;
};
}
// Exemplo de uso:
const cipher = new VigenèreCipher("KEY", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
const encoded = cipher.encode("HELLO"); // Retorna "RIJVS"
const decoded = cipher.decode("RIJVS"); // Retorna "HELLO"