Skip to content

Instantly share code, notes, and snippets.

@shonenada
Created September 15, 2016 16:38
Show Gist options
  • Save shonenada/f4a43f5d7b4b25bc29c08abcbf3ed47a to your computer and use it in GitHub Desktop.
Save shonenada/f4a43f5d7b4b25bc29c08abcbf3ed47a to your computer and use it in GitHub Desktop.
import string
from random import choice
from Crypto import Random
from Crypto.Cipher import AES
KEY = ''.join([choice(string.printable) for i in range(16)])
def padding(text, bs):
return ''.join([text, (bs - len(text) % bs) * chr(bs - len(text) % bs)])
def unpadding(text):
return text[:-ord(text[-1])]
def encrypt(text):
iv = Random.new().read(AES.block_size)
aes = AES.new(KEY, AES.MODE_CBC, iv)
return ''.join([iv, aes.encrypt(padding(text, AES.block_size))])
def decrypt(cipher):
iv, ci = cipher[:16], cipher[16:]
aes = AES.new(KEY, AES.MODE_CBC, iv)
return unpadding(aes.decrypt(ci))
if __name__ == '__main__':
while True:
msg = raw_input('Msg: ')
bytes_msg = str.encode(msg)
print len(bytes_msg)
cipher = encrypt(bytes_msg)
print 'Encrypt:', cipher
print 'Decrypt:', decrypt(cipher)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment