Introduction
In this lab, we will explore the Caesar cipher, a simple encryption algorithm that shifts each letter of a given string by a certain number of positions down the alphabet. We will implement the Caesar cipher in JavaScript, using a combination of string manipulation and array methods, and learn how to encrypt and decrypt messages with this technique. This lab is an excellent opportunity to practice your JavaScript skills and gain a better understanding of encryption algorithms.
Caesar Cipher
To use the Caesar cipher, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Call the
caesarCipherfunction with the string to be encrypted or decrypted, the shift value, and a boolean indicating whether to decrypt or not. - The
caesarCipherfunction uses the modulo (%) operator and the ternary operator (?) to calculate the correct encryption or decryption key. - It uses the spread operator (
...) andArray.prototype.map()to iterate over the letters of the given string. - It uses
String.prototype.charCodeAt()andString.fromCharCode()to convert each letter appropriately, ignoring special characters, spaces, etc. - It uses
Array.prototype.join()to combine all the letters into a string. - If you want to decrypt an encrypted string, pass
trueto the last parameter,decrypt, when calling thecaesarCipherfunction.
Here is the code for the caesarCipher function:
const caesarCipher = (str, shift, decrypt = false) => {
const s = decrypt ? (26 - shift) % 26 : shift;
const n = s > 0 ? s : 26 + (s % 26);
return [...str]
.map((l, i) => {
const c = str.charCodeAt(i);
if (c >= 65 && c <= 90)
return String.fromCharCode(((c - 65 + n) % 26) + 65);
if (c >= 97 && c <= 122)
return String.fromCharCode(((c - 97 + n) % 26) + 97);
return l;
})
.join("");
};
Here are some examples of how to use the caesarCipher function:
caesarCipher("Hello World!", -3); // 'Ebiil Tloia!'
caesarCipher("Ebiil Tloia!", 23, true); // 'Hello World!'
Summary
Congratulations! You have completed the Caesar Cipher lab. You can practice more labs in LabEx to improve your skills.