24th February, 2017

ROT13 in Python

A simple ROT13 algorithm in Python 3.5.

This is a Python 3.5 script for ciphering strings using ROT.
https://en.wikipedia.org/wiki/ROT13, https://en.wikipedia.org/wiki/Caesar_cipher. You can find this project on my GitHub by clicking here.

This is a simple plug-and-play ROT function. Simply pass the cipher function a string, key, shift value, and mode (1 for encipher, and -1 for decipher) and the function will return a enciphered / deciphered string.
It is possible to use any key and any shift value with this function. If a character is not found in the key, it is just added to the final output string.

I am currently using this script to power the web page enciphering engine behind wsantos.io/p, which is a web proxy that remotely fetches web pages and enciphers the text so that it cannot trigger any HTTP/HTTPS packet inspection system. There is JavaScript function on the user's end that deciphers the text and then displays the web page.

Source code

  
# the symmetric key used to encipher / decipher characters
key = "abcdefghijklmnopqrstuvwxyz"
# how many places to shift each letter in the key
shift = 13
# 1 = encipher / -1 = decipher
mode = 1


def cipher(string, key, shift, mode):
    # initialise output list
    output = []
    for char in string:
        # encipher / decipher the character only if it is in the key
        if char in key:
            # the pointer is equal to the position of the character in the key plus the shift value multiplied by the mode
            pointer = key.index(char) + shift * mode
            # append the value at the position of the pointer modulus the length of the key (wrap around)
            output.append(key[pointer % len(key)])
        # if the character is not in the key just append it to the output list
        else:
            output.append(char)
    # concatenate all characters in the output list and return as a string
    return ''.join(output)

print(cipher("william", key, shift, mode))
  

Example usage

  
key = "abcdefghijklmnopqrstuvwxyz" # the symmetric key used to encipher / decipher characters
shift = 13 # how many places to shift each letter in the key
mode = 1 # 1 = encipher / -1 = decipher
...
print(cipher("hello world", key, shift, mode))
# Returns "uryyb jbeyq"
  

Thank you for reading.

🚀🚀🚀


Leave a comment

Invalid or missing field(s).
Comment sent successfully, please wait for it to be approved.

This post has no comments