The Caesar Cypher is a simple encryption technique that is around 2000 years old. It is categorized as a symmetric encryption type since it requires a private key that is used for both encryption and decryption. How does it work? This cypher algorithm is fairly simple, given an alphabet, each letter corresponds to a number. The key also translates to a number. Then each character of the secret message is shifted n number of times where n is the key number, and the character is substituted with the alphabet letter in the shifted position.

For instance the letters might be inserted in an array, therefore each letter will have a corresponding index position.

Suppose the secret message has the letter A in it and the key is 2 then the letter A will be shifted by two and becoming C.

Here follows my implementation in typescript. I have decided to make the cypher case sensitive and also replace empty spaces.

The constructor initializes the alpha numeric string of characters supported by this implementation. In addition to that it defines the operations for encrypting shift forward and decrypting shift backwards.

Javascript built in modulo is not really a modulo function but rather a reminder. This helper methods allows % to work with negative integers.

This method is responsible for returning the key code number. The function takes in a character and looks up the char position in the alpha numeric string variable.

The caesarCypher function holds the logic of the algorithm. Once the key code is calculated then the function operates the character shifting. Both encrypt and decrypt follows the same logic exception made for the shifting. Encrypt shifts forward while decrypt shifts backwards. The method uses the operations variable that is defined in the constructor to determine the shift direction.

The snippets above shows how encryption and decryption becomes fairly simple to invoke.

The tests shows how this caesarCypher implementation can be used to encrypt and decrypt messages. The complete source code for this example can be found here.