-
Notifications
You must be signed in to change notification settings - Fork 0
/
vigenereCipher.js
96 lines (75 loc) · 2.07 KB
/
vigenereCipher.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// JavaScript code to implement Vigenere Cipher
// This function generates the key in
// a cyclic manner until it's length isn't
// equal to the length of original text
function generateKey(str,key)
{
key=key.split("");
if(str.length == key.length)
return key.join("");
else
{
let temp=key.length;
for (let i = 0;i<(str.length-temp) ; i++)
{
key.push(key[i % ((key).length)])
}
}
return key.join("");
}
// This function returns the encrypted text
// generated with the help of the key
function cipherText(str,key)
{
let cipher_text="";
for (let i = 0; i < str.length; i++)
{
// converting in range 0-25
let x = (str[i].charCodeAt(0) + key[i].charCodeAt(0)) %26;
// convert into alphabets(ASCII)
x += 'A'.charCodeAt(0);
cipher_text+=String.fromCharCode(x);
}
return cipher_text;
}
// This function decrypts the encrypted text
// and returns the original text
function originalText(cipher_text,key)
{
let orig_text="";
for (let i = 0 ; i < cipher_text.length ; i++)
{
// converting in range 0-25
let x = (cipher_text[i].charCodeAt(0) -
key[i].charCodeAt(0) + 26) %26;
// convert into alphabets(ASCII)
x += 'A'.charCodeAt(0);
orig_text+=String.fromCharCode(x);
}
return orig_text;
}
// This function will convert the lower
// case character to Upper case
function LowerToUpper(s)
{
let str =(s).split("");
for(let i = 0; i < s.length; i++)
{
if(s[i] == s[i].toLowerCase())
{
str[i] = s[i].toUpperCase();
}
}
s = str.toString();
return s;
}
// Driver code
let str = "SIMFITKXLLVOB";
let keyword = "DEVDEGREE";
let key = generateKey(str, keyword);
let cipher_text = cipherText(str, key);
console.log("Ciphertext : "
+ cipher_text);
console.log("Original/Decrypted Text : "
+ originalText(cipher_text, key));
// This code is contributed by rag2127