Skip to content

Instantly share code, notes, and snippets.

@tormath1
Created June 10, 2020 08:55
Show Gist options
  • Save tormath1/e75508d75453c0ad980b7b4d513e9167 to your computer and use it in GitHub Desktop.
Save tormath1/e75508d75453c0ad980b7b4d513e9167 to your computer and use it in GitHub Desktop.
OTP - Encryt / Decrypt example
import sys
import string
import random
# return a key of the size
# of the PT
def generate_key(length):
r = lambda: \
string.ascii_letters[int(random.random() * len(string.ascii_letters))]
key = b''
for k in range(length):
key += bytes(r().encode())
return key
def encrypt(msg: bytes):
length = len(msg)
key = generate_key(length)
i = 0
c = b''
while i < length:
c += bytes(chr(key[i] ^ msg[i]).encode())
i += 1
return c, key
def decrypt(c: bytes, key: bytes):
i = 0
m = b''
while i < len(key):
m += bytes(chr(key[i] ^ c[i]).encode())
i += 1
return m
if __name__ == "__main__":
if len(sys.argv) < 2:
print("usage: python otp.py <message>")
exit(0)
msg = sys.argv[1]
c, k = encrypt(bytes(msg.encode()))
print(decrypt(c, k))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment