Created
August 3, 2017 14:26
-
-
Save sourceperl/9163f62c495bc458595fb8101326655e to your computer and use it in GitHub Desktop.
Test of AES128 with python3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
from Crypto.Cipher import AES | |
import hashlib | |
import os | |
# message to crypt with AES-128 | |
text = 'the secret message' | |
# define 128-bit key from a text password | |
tx_key_128 = hashlib.md5(b'password').digest() | |
# initialization vector | |
tx_iv = os.urandom(16) | |
# text to crypt must be modulo 16 sized: add \x00 padding | |
ptxt = text.encode('utf8') | |
ptxt += b'\x00' * (16 - len(ptxt) % 16) | |
# do encrypt job | |
encryptor = AES.new(tx_key_128, AES.MODE_CBC, IV=tx_iv) | |
tx_ctxt = encryptor.encrypt(ptxt) | |
# build message to send on public network | |
pub_msg = tx_iv + tx_ctxt | |
# read from public message | |
rx_key_128 = hashlib.md5(b'password').digest() | |
rx_iv = pub_msg[:16] | |
rx_ctxt = pub_msg[16:] | |
# do decrypt job | |
decryptor = AES.new(rx_key_128, AES.MODE_CBC, IV=rx_iv) | |
plain = decryptor.decrypt(rx_ctxt) | |
# remove text padding | |
plain = plain.rstrip(b'\x00') | |
# result | |
print(plain.decode('utf8')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment