External Exam Download Resources Web Applications Games Recycle Bin

One-time pad (OTP)

onetimepad_cipher.py

#one_time_pad cipher
#type of Vignere cipher, including the following features:
#1) unbreakable (random, auto-generated)
#2) key is made up of random symbols
#3) key used one time and thrown away

plain_text = "THISISSECRET"
OTP_key = "XVHEUWNOPGDZ"
plain_chars = list(plain_text)
OTP_chars = list(OTP_key)

# to encrypt:
encrypted_chars = []
for i, char in enumerate(OTP_chars):
    #ord("A")=65, so A means shift 0,
    #B means shift 1, etc:
    shift_amount = ord(char) - ord("A")
    plain_char_ord = ord(plain_chars[i]) - ord("A") 
    
    #find out new char ord:
    new_char_ord = plain_char_ord + shift_amount
    #if the new char ord > 26, then wrap around to 0 (Z to A):
    new_char_ord = new_char_ord % 26

    #revert back to correct character ordinals:
    encrypted_chars.append(chr(new_char_ord+ord("A")))

cipher_text = "".join(encrypted_chars)
print(cipher_text)