Last active
March 14, 2021 00:09
-
-
Save ilhamarrouf/836d6b09066a3dcfbe143bd5b5d1467f to your computer and use it in GitHub Desktop.
Vigenete Cipher
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function isUpperCase(letter){ | |
let l = letter.charCodeAt(); | |
return l >= 65 && l <= 90; | |
} | |
function isLowerCase(letter){ | |
let l = letter.charCodeAt(); | |
return l >= 97 && l <= 122; | |
} | |
function encrypt(plainMsg, key){ | |
let cipher = ""; | |
for(let i = 0, j = 0; i < plainMsg.length; i++){ | |
let currentLetter = plainMsg[i]; | |
switch (true) { | |
case isUpperCase(currentLetter): | |
let upperLetter = ((currentLetter.charCodeAt() - 65) | |
+ (key[j%key.length].toUpperCase().charCodeAt() - 65)) | |
% 26; | |
cipher += String.fromCharCode(upperLetter+65); | |
j++; | |
break; | |
case isLowerCase(currentLetter): | |
let lowerLetter = ((currentLetter.charCodeAt() - 97) | |
+ (key[j%key.length].toLowerCase().charCodeAt() - 97)) | |
% 26; | |
cipher += String.fromCharCode(lowerLetter+97); | |
j++; | |
break; | |
default: | |
cipher += currentLetter; | |
break; | |
} | |
} | |
return cipher; | |
} | |
function decrypt(cipher, key) { | |
let plainMsg = ''; | |
for(let i = 0, j = 0; i < cipher.length; i++){ | |
let currentLetter = cipher[i]; | |
switch (true) { | |
case isUpperCase(currentLetter): | |
let upperLetter = ((currentLetter.charCodeAt() - 65) | |
- (key[j%key.length].toUpperCase().charCodeAt() - 65) | |
+ 26) | |
% 26; | |
plainMsg += String.fromCharCode(upperLetter + 65); | |
j++; | |
break; | |
case isLowerCase(currentLetter): | |
let lowerLetter = ((currentLetter.charCodeAt() - 97) | |
- (key[j%key.length].toLowerCase().charCodeAt() - 97) | |
+ 26) | |
% 26; | |
plainMsg += String.fromCharCode(lowerLetter + 97); | |
j++; | |
break; | |
default: | |
plainMsg += currentLetter; | |
break; | |
} | |
} | |
return plainMsg; | |
} | |
console.log(encrypt('pawn', 'secret')) | |
console.log(decrypt('heye', 'secret')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment