|
| 1 | +/** |
| 2 | + * Check if the Character is letter or not |
| 3 | + * @param {String} character - character to check |
| 4 | + * @return {object} An array with the character or null if isn't a letter |
| 5 | + */ |
| 6 | +function isLetter(str) { |
| 7 | + return str.length === 1 && str.match(/[a-zA-Z]/i); |
| 8 | +} |
| 9 | + |
| 10 | +/** |
| 11 | + * Check if is Uppercase or Lowercase |
| 12 | + * @param {String} character - character to check |
| 13 | + * @return {Boolean} result of the checking |
| 14 | + */ |
| 15 | +function isUpperCase(character){ |
| 16 | + if (character == character.toUpperCase()) { |
| 17 | + return true; |
| 18 | + } |
| 19 | + if (character == character.toLowerCase()){ |
| 20 | + return false; |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +/** |
| 25 | + * Encrypt a Vigenere cipher |
| 26 | + * @param {String} message - string to be encrypted |
| 27 | + * @param {String} key - key for encrypt |
| 28 | + * @return {String} result - encrypted string |
| 29 | + */ |
| 30 | +function encrypt(message, key) |
| 31 | +{ |
| 32 | + |
| 33 | + let result = ""; |
| 34 | + |
| 35 | + for (let i = 0, j = 0; i < message.length; i++) { |
| 36 | + let c = message.charAt(i); |
| 37 | + if (isLetter(c)){ |
| 38 | + if(isUpperCase(c)) { |
| 39 | + result += String.fromCharCode((c.charCodeAt(0) + key.toUpperCase().charCodeAt(j) - 2 * 65) % 26 + 65); // A: 65 |
| 40 | + } else { |
| 41 | + result += String.fromCharCode((c.charCodeAt(0) + key.toLowerCase().charCodeAt(j) - 2 * 97) % 26 + 97); // a: 97 |
| 42 | + } |
| 43 | + } else { |
| 44 | + result+=c; |
| 45 | + } |
| 46 | + j = ++j % key.length; |
| 47 | + } |
| 48 | + return result; |
| 49 | +} |
| 50 | + |
| 51 | +/** |
| 52 | + * Decrypt a Vigenere cipher |
| 53 | + * @param {String} message - string to be decrypted |
| 54 | + * @param {String} key - key for decrypt |
| 55 | + * @return {String} result - decrypted string |
| 56 | + */ |
| 57 | +function decrypt(message, key) |
| 58 | +{ |
| 59 | + let result =""; |
| 60 | + |
| 61 | + for(let i = 0, j = 0; i < message.length; i++){ |
| 62 | + let c = message.charAt(i); |
| 63 | + if (isLetter(c)){ |
| 64 | + if(isUpperCase(c)) { |
| 65 | + result += String.fromCharCode(90-(25-(c.charCodeAt(0)-key.toUpperCase().charCodeAt(j)))%26); |
| 66 | + } else { |
| 67 | + result += String.fromCharCode(122-(25-(c.charCodeAt(0)-key.toLowerCase().charCodeAt(j)))%26); |
| 68 | + } |
| 69 | + } else { |
| 70 | + result+=c; |
| 71 | + } |
| 72 | + j = ++j % key.length; |
| 73 | + } |
| 74 | + return result; |
| 75 | +} |
| 76 | + |
| 77 | +let messageEncrypt = encrypt('Hello World!', 'code'); |
| 78 | +console.log(messageEncrypt); // "Jhpnr Yrvng!" |
| 79 | + |
| 80 | +let messageDecrypt = decrypt('Jsopq Zstzg!', 'code'); |
| 81 | +console.log(messageDecrypt); // "Hello World!" |
0 commit comments