How to write One-Time Pad cipher in Python

770 views Asked by At

Based on Wikipedia, One-Time Pad is an encryption technique that cannot be cracked. How to implement One-Time Pad encryption in Python?

1

There are 1 answers

1
Farshid Ashouri On

Here is an example implementation

def encrypt(pad, secret):
    return ''.join([chr(ord(c) ^ ord(secret[i])) for i, c in enumerate(pad[:len(secret)])])

Now you can use it to encrypt your messages. Remember the pad size should be at least the size of the secret:

secret = 'i am a secret'
pad = '33116f14-9b6f-42c6-9636-3dbd31c0548d'
enc = encrypt(pad, secret)

And you can decipher it with the same function:

assert secret == encrypt(pad, enc)