Skip to content

Instantly share code, notes, and snippets.

@kernelshreyak
Created July 28, 2022 15:48
Show Gist options
  • Save kernelshreyak/422cae823202e5cd91e91198b2291cab to your computer and use it in GitHub Desktop.
Save kernelshreyak/422cae823202e5cd91e91198b2291cab to your computer and use it in GitHub Desktop.
Implementation of One Time Pad Cipher in Python
import os
import base64
class OneTimePad:
def encode_cipher(self,_string, key):
key = base64.b64decode(key)
retval = []
for k, v in zip(_string, key):
retval.append(int(ord(k) ^ v))
return base64.b64encode(bytes(retval))
def decode_cipher(self,encoded, key):
retval = []
encoded = base64.b64decode(encoded)
key = base64.b64decode(key)
for k, v in zip(encoded, key):
retval.append(int(k ^ v))
return bytes(retval)
plaintext = "hello how are you"
key = base64.b64encode(os.urandom(len(plaintext)))
cipher = OneTimePad()
ciphertext = cipher.encode_cipher(plaintext,key)
plaintext2 = cipher.decode_cipher(ciphertext,key)
print("Encrypted:",ciphertext)
print("Decrypted:",plaintext2)
@kernelshreyak
Copy link
Author

This is not a practical cipher but highly secure since the encryption key is random every time and has same length as that of the message

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment