function
stringEncryption(text, key) {
let cipherText =
""
;
let cipher = [];
for
(let i = 0; i < key.length; i++) {
cipher[i] = text.charCodeAt(i) - 'A
'.charCodeAt(0) + key.charCodeAt(i) - '
A
'.charCodeAt(0);
}
// If the sum is greater than 25
// subtract 26 from it
// and store that resulting value
for (let i = 0; i < key.length; i++) {
if (cipher[i] > 25) {
cipher[i] = cipher[i] - 26;
}
}
// Converting the no.'
s into integers
for
(let i = 0; i < key.length; i++) {
let x = cipher[i] +
'A'
.charCodeAt(0);
cipherText += String.fromCharCode(x);
}
return
cipherText;
}
function
stringDecryption(s, key) {
let plainText =
""
;
let plain = [];
for
(let i = 0; i < key.length; i++) {
plain[i] = s.charCodeAt(i) - 'A
'.charCodeAt(0) - (key.charCodeAt(i) - '
A
'.charCodeAt(0));
}
// If the difference is less than 0
// add 26 and store it in the array.
for (let i = 0; i < key.length; i++) {
if (plain[i] < 0) {
plain[i] = plain[i] + 26;
}
}
// Converting int to corresponding char
// add them up to plainText
for (let i = 0; i < key.length; i++) {
let x = plain[i] + '
A'.charCodeAt(0);
plainText += String.fromCharCode(x);
}
return
plainText;
}
function
main() {
let plainText =
"Hello"
;
let key =
"MONEY"
;
plainText = plainText.toUpperCase();
key = key.toUpperCase();
let encryptedText = stringEncryption(plainText, key);
console.log(
"Cipher Text - "
+ encryptedText);
console.log(
"Message - "
+ stringDecryption(encryptedText, key));
}
main();