-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvigenere.js
71 lines (59 loc) · 1.98 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function vigenereEncrypt(plainText, keyword) {
let result = '';
let keywordIndex = 0;
for (let i = 0; i < plainText.length; i++) {
let char = plainText[i];
if (char >= 'A' && char <= 'Z') {
let shift = keyword[keywordIndex % keyword.length].toUpperCase().charCodeAt(0) - 65;
result += String.fromCharCode((char.charCodeAt(0) + shift - 65) % 26 + 65);
keywordIndex++;
}
else if (char >= 'a' && char <= 'z') {
let shift = keyword[keywordIndex % keyword.length].toLowerCase().charCodeAt(0) - 97;
result += String.fromCharCode((char.charCodeAt(0) + shift - 97) % 26 + 97);
keywordIndex++;
}
else {
result += char;
}
}
return result;
}
function vigenereDecrypt(cipherText, keyword) {
let result = '';
let keywordIndex = 0;
for (let i = 0; i < cipherText.length; i++) {
let char = cipherText[i];
if (char >= 'A' && char <= 'Z') {
let shift = keyword[keywordIndex % keyword.length].toUpperCase().charCodeAt(0) - 65;
result += String.fromCharCode((char.charCodeAt(0) - shift + 26 - 65) % 26 + 65);
keywordIndex++;
}
else if (char >= 'a' && char <= 'z') {
let shift = keyword[keywordIndex % keyword.length].toLowerCase().charCodeAt(0) - 97;
result += String.fromCharCode((char.charCodeAt(0) - shift + 26 - 97) % 26 + 97);
keywordIndex++;
}
else {
result += char;
}
}
return result;
}
rl.question('Enter plain text: ', (plainText) => {
rl.question('Enter keyword: ', (keyword) => {
// Encrypt the plain text
const cipherText = vigenereEncrypt(plainText, keyword);
console.log("Encrypted text: " + cipherText);
// Decrypt the cipher text
const decryptedText = vigenereDecrypt(cipherText, keyword);
console.log("Decrypted text: " + decryptedText);
// Close the readline interface
rl.close();
});
});