Encrypt and decrypt using the Caesar cipher
I have always been intrigued with different encryption techniques ever since I was in the very beginning of my software engineering journey. I remember in our security class at the university where we were asked to solve the Caesar cipher algorithm, and I thought I would dust of my old memories and share a solution with you.
In this guide, I will share how we can encrypt a text and then decrypt it using JavaScript.
If you are looking for a secure way of encrypting passwords or other texts, check out our free Crypto API.
What is Caesar cipher and how does it work
This algorithm is (I think) the oldest known encryption algorithm that has its roots back to 58 BC, it also one of the simplest ones so consider using something else if you want to encrypt secret content :)
The logic is simple, a text will be encrypted by a number e.g 1 and then all the letters will change to the next character of the alphabet. So for example the work Cat would be Dbu if the number provided is 1.
Create our encryption algorithm
All right, let's dive into the fun part. We will start by creating our encryption function. It will accept a text and a number as its arguments.
But first, let's assign our alphabet constant
const alphabet = [ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", ];
And now, we will create our encryption function. I will explain the key parts below.
const encrypt = (text, number) => { if (!text?.length || number < 1) { return ""; } let encrypted = ""; [...text].forEach((letter) => { if (letter === " ") { encrypted += " "; } else { const isUpperCase = letter === letter.toUpperCase(); const originalIndex = alphabet.findIndex( (a) => a === letter.toUpperCase() ); let newIndex = originalIndex + number; // If new index is higher than the length, we need to start over in the alphabet if (newIndex >= alphabet.length) { // We will substract the length of the alphabet to find our new index while (newIndex >= alphabet.length) { newIndex -= alphabet.length; } } // Add the new character to the new string encrypted += isUpperCase ? alphabet[newIndex] : alphabet[newIndex].toLowerCase(); } }); return encrypted; };
Notes of the code
-
First step is to check that the text is a valid string, and that the shift number is > 0
-
Then we loop through each character, even spaces
-
If the letter is a space, we simple add a space to our encrypted string
-
Then we check if the character is an upper case letter or not
-
The we find the original index in the alphabet
-
Our newIndex will be original index + shift number
-
If newIndex is greater than the length of the alphabet, we need to substract the length until the newIndex is in range of our array
-
And in the end of the loop, we add the new character to the encrypted string. And to make it accurate, we check if it should be upper or lower case.
Encrypt our texts
I will a couple of tests to do some encryption
console.log(encrypt("secret text", 45)); // lxvkxm mxqm console.log(encrypt("cat", 15)); // rpi console.log(encrypt("Algobook", 56)); // Epksfsso
And now, we will decrypt it as well.
Decryption
Let's write our decryption function. It should basically do the same, but in reverse order for the alphabet index.
const decrypt = (text, number) => { if (!text?.length || number < 1) { return ""; } let decrypted = ""; [...text].forEach((letter) => { if (letter === " ") { decrypted += " "; } else { const isUpperCase = letter === letter.toUpperCase(); const originalIndex = alphabet.findIndex( (a) => a === letter.toUpperCase() ); let newIndex = originalIndex - number; // If new index is less than 0, we need to add the length of the alphabet to find the new index if (newIndex < 0) { while (newIndex < 0) { newIndex += alphabet.length; } } // Add the new character to the new string decrypted += isUpperCase ? alphabet[newIndex] : alphabet[newIndex].toLowerCase(); } }); return decrypted; };
Notes
- The only difference here is the finding logic of the newIndex where we instead are adding the alphabet length until the newIndex is >= 0
Decrypt our texts
Let's see if it works then.
console.log(decrypt("lxvkxm mxqm", 45)); // secret text console.log(decrypt("rpi", 15)); // cat console.log(decrypt("Epksfsso", 56)); // Algobook
There we go!
Outro
In this article, we covered the Caesar cipher and how we can implement it in our JavaScript application. Algorithms like this are perfect challenges for junior developers that are looking to extend their coding skills, and even for more experienced devlopers that need to dust of old knowledge :)
I hope you enjoyed this article, and if you are looking for encryption for your application, have a look at our free Crytop API or implement your own hashing with help from this article.
Thanks for reading, have a great day!