ROT13 encoding is definitely not the most secure method of encoding anything. Typically, ROT13 was used many years ago to hide offensive jokes on forums as a kind of Not Safe For Work (NSFW) tag so people wouldn't instantly see the remark. These days, it's mostly used within Capture The Flag (CTF) challenges, and you'll find out why.
For this script, we will need quite specific modules. We will be needing the maketrans
feature, and the lowercase and uppercase features from the string
module.
To use the ROT13 encoding method, we need to replicate what the ROT13 cipher actually does. The 13 indicates that each letter will be moved 13 places along the alphabet scale, which makes the encoding very easy to reverse:
from string import maketrans, lowercase, uppercase def rot13(message): lower = maketrans(lowercase, lowercase[13:] + lowercase[:13]) upper = maketrans(uppercase, uppercase[13:] + uppercase[:13]) return message.translate(lower).translate(upper) message = raw_input('Enter :') print rot13(message)
This is the first of our scripts that doesn't simply require the hashlib
module; instead it requires specific features from a string. We can import these using the following:
from string import maketrans, lowercase, uppercase
Next, we can create a block of code to do the encoding for us. We use the maketrans
feature of Python to tell the interpreter to move the letters 13 places across and to keep uppercase within the uppercase and lower within the lower. We then request that it returns the value to us:
def rot13(message): lower = maketrans(lowercase, lowercase[13:] + lowercase[:13]) upper = maketrans(uppercase, uppercase[13:] + uppercase[:13]) return message.translate(lower).translate(upper)
We then need to ask the user for some input so we have a string to work with; this is done in the traditional way:
message = raw_input('Enter :')
Once we have the user input, we can then print out the value of our string being passed through our rot13
block of code:
print rot13(message)
The following is an example of the code in use:
Enter :This is an example of encoding in Python Guvf vf na rknzcyr bs rapbqvat va Clguba