In cryptography, a Caesar cipher, also known as Caesar's cipher, the shift cipher, Caesar's code or Caesar shift, is one of the simplest and most widely known encryption techniques. It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example, with a left shift of 3, D would be replaced by A, E would become B, and so on. The method is named after Julius Caesar, who used it in his private correspondence.
The encryption step performed by a Caesar cipher is often incorporated as part of more complex schemes, such as the Vigenère cipher, and still has modern application in the ROT13 system. As with all single-alphabet substitution ciphers, the Caesar cipher is easily broken and in modern practice offers essentially no communications security.
For example, shifting each of the 26 letters of the English alphabet by 3 places to the left, is equivalent to shifting by 23 places to the right. A plain text message without encryption applied is below:
Plaintext: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
To take a look at what is going on, we can take the letter A. shifting A to the left by 3 places, with 1 shift, we get Z, with 2 shifts, we get Y and with 3rd shift we get X. With this cipher, this is done for all letters of the alphabet and shifted.
Ciphertext: QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD
To decrypt, one will need to shift each letter of the encrypted in the opposite direction to which it was shifted. So A is now X, to get back to A, we shift to the right by 3 to get back to A.
In order to do this computationally, this encryption uses modular arithmetic by transforming the letters to numbers. Computers use ASCII code. From ASCII tables, A is 65, counting incrementally until Z is 90, and a is 97, counting incrementally to z which is 122.
The complete code is given below:
const caesarCipher = (str, shift=13) => str.replace( /[A-Za-z]/g, char => String.fromCharCode( 65 + ((char = char.charCodeAt()) & 32) +((char&~32) - 65 + shift) % 26 ) )
char.charCodeAt() merely transforms the given character, char to its ASCII number, while the
String.fromCharCode() method transforms the given number back to its alphabetic form. Now using this inside the
Array.prototype.replace() method, we are simply replacing a given English alphabet with a shifted ASCII alphabet, thus scrambling the message.
It is worth noting that Caesar cipher is one of the most famous encryption algorithms in simplicity and cannot offer any information security.
Top comments (4)
The code needs fixing:
Thanks Jon. I love this.
Also, to get JS syntax highlighting in your post - add
jsafter the opening 3 backticks 👍