Today we’ll show you some ROT13 Python code and explain how it works. We’ll be using Python 3.8.10. Let’s go! ✨⚡
ROT13 or ROT-13 is a letter substitution cipher that replaces each letter of the message to be encoded, with the 13th after it in the alphabet. ROT is actually an acronym for “rotate by 13 places”. Simple, right?
Let’s write some code:
abc = "abcdefghijklmnopqrstuvwxyz"
m = "xgetxbetterxbyxcodingxdaily"
rt13 = lambda x: "".join([abc[(abc.find(c) + 13) % 26] for c in x])
print(rt13(m))
#output
#ktrgkorggrekolkpbqvatkqnvyl
Let’s explain what is going on here:
- We declare the alphabet as abc. We include all letters from A to Z.
- We declare our message m which is the plaintext. The actual message is “get better by coding” but we include a leading and trailing x as well as include x in the whitespace. Remember that a whitespace is technically a character but it doesn’t exist in the alphabet so it’ll confuse the algorithm.
- Recall that a lambda function in Python is an anonymous inline function with one expression. In this case the expression is substituting each letter of our plaintext with the 13th letter to the right of it in abc. The expression will also wrap around and start counting at the beginning of abc if the 13th letter reaches beyond the end of the string.
- We pass our original plaintext m to the lambda function rt13 and we get our ciphertext which we print to the screen i.e. the encrypted plaintext after the substitution is applied.
Nice! If all goes well, you should see a message printed to the screen that looks like gibberish. This is exactly what we want to see.
It turns out that the ROT13 algorithm is very very easy to crack. All we have to do is apply the same algorithm to the ciphertext, once we know that ROT13 was used to encrypt the data, and we can crack it:
print(rt13(rt13(s)))
#output
#xgetxbetterxbyxcodingxdaily
See how easy that was? We simply apply the same algorithm to the ciphertext to undo the encryption and voila, we have the original message!
Here’s the entire script:
abc = "abcdefghijklmnopqrstuvwxyz"
m = "xgetxbetterxbyxcodingxdaily"
rt13 = lambda x: "".join([abc[(abc.find(c) + 13) % 26] for c in x])
#encrypt plaintext
print(rt13(m))
#decrypt ciphertext
print(rt13(rt13(m)))
Note that ROT13 is not a good way to secure data, obviously. It is a well known algorithm that is easily cracked once one knows that it was used to encrypt the original data. The above code is for education purposes only. Use at your own risk!
Thanks for reading! Find another great tutorial on encryption HERE. Good luck! 👌👌👌