Caesar cipher and ROT13 encoding/decoding in bash

2018-02-21

Caesar Ciphers is one of the most simple and commonly known encoding algorithms. It is named after Julius Caesar, the Roman emperor, who regularly used it in its letter. Its simplicity lies in the fact that each letter is replaced with another letter three positions later down the alphabet, with XYZ going back to ABC. The encoded alphabet, with respect to the regular alphabet, will look like the following:

Plain:     ABCDEFGHIJKLMNOPQRSTUVWXYZ
Encoded:   XYZABCDEFGHIJKLMNOPQRSTUVW

ROT13, is a slightly modifed version of the algorithm in which the letters, instead of being shifted by three position are shifted, as one might imagine, by 13. The encoded alphabet, then, is:

Plain:     ABCDEFGHIJKLMNOPQRSTUVWXYZ
Encoded:   NOPQRSTUVWXYZABCDEFGHIJKLM

Sometimes, it might be required to perform encoding/decoding using this ciphers from the command line (although nowadays base64 is more commonly used). In case you find yourself needing to perform these operations, these quick commands will help you perform the required operations:

# Encode using Caesar Cipher
echo "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG" | tr '[A-Z]' '[X-ZA-W]'
# output: QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD

# Decode using Caesar cipher
echo "QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD" | tr '[X-ZA-W]' '[A-Z]'
# output: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG

# Encode using ROT-13
echo "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG" | tr '[A-Z]' '[N-ZA-M]'
# output: GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT

# Decode using ROT-13
echo "GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT" | tr '[N-ZA-M]' '[A-Z]'
# output: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG

# Performe a case sensitive encoding using ROT13
tr '[A-Za-z]' '[N-ZA-Mn-za-m]'

The story behind the Caesar Cipher and how it was first cracked is very interesting. If you would like to learn more I suggest you read up something about it on Wikipedia, you can find it at this link.

Pietro Bongiovanni

I'm Pietro, I like to build things with software.

Right now, I am helping mollie scale online payments
across Europe and the rest of the world.
Join us!