Skip to content

Instantly share code, notes, and snippets.

@jlinoff
Created December 11, 2015 17:43
Show Gist options
  • Save jlinoff/246bc8386081fdf4b24f to your computer and use it in GitHub Desktop.
Save jlinoff/246bc8386081fdf4b24f to your computer and use it in GitHub Desktop.
Python example that shows how to use the pycrypto (Crypto) module to do AES encryption and decryption.
#!/usr/bin/env python
'''
Simple example of how to use the crypto library for AES encryption and
decryption.
Make sure that the Crypto (pycrypto) module is installed:
$ pip-2.7 install pycrypto
$ pip-3.5 install pycrypto
Then run this script. You will see output that looks something like
this:
$ python3 aes_example.py
test01 - running ...
test01 - ok
test02 - running 10000 ...
test02 - ok
It might take up to 10 seconds to run the second test.
This script has been tested with Python 2.7, 3.4 and 3.5.
Please note that this script cannot be used to compare the performance
of different versions of Python because the data and passwords are
randomly generated on each run.
LICENSE (MIT Open Source)
Copyright (c) 2015 Joe Linoff
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'''
import base64
# pycrypto module
from Crypto import Random
from Crypto.Cipher import AES
class AESCipher:
'''
Object that encrypts and decrypts using AES.
Usage:
password = 'password'
aes = AESCipher(password)
data = 'this, that, the other'
enc = aes.encrypt(data)
dec = aes.decrypt(enc)
assert enc = dec
'''
def __init__(self, key):
self.m_bs = 32
self.m_key = key[:32] if len(key) >= 32 else self._pad(key)
def encrypt(self, raw):
raw = self._pad(raw)
iv = Random.new().read(AES.block_size)
cipher = AES.new(self.m_key, AES.MODE_CBC, iv)
return base64.b64encode(iv + cipher.encrypt(raw))
def decrypt(self, enc):
enc = base64.b64decode(enc)
iv = enc[:AES.block_size]
cipher = AES.new(self.m_key, AES.MODE_CBC, iv)
return self._unpad(cipher.decrypt(enc[AES.block_size:]))
def _pad(self, s):
return s + (self.m_bs - len(s) % self.m_bs) * chr(self.m_bs - len(s) % self.m_bs)
def _unpad(self, s):
return s[:-ord(s[len(s)-1:])]
def test01():
'''
Simple test module.
This is a simple aliveness test.
'''
print('test01 - running ...')
aes = AESCipher('password')
plain = 'this that the other'
enc = aes.encrypt(plain)
dec = aes.decrypt(enc).decode('ascii')
if plain != dec:
print('test01 - failed')
assert plain == dec
print('test01 - ok')
def test02(num=10000):
'''
More complex test.
'''
print('test02 - running {} ...'.format(num))
# Define the alphabets for the data and the password.
# They could easily be different but that is not necessary
# for this test.
import string
data_alphabet = string.ascii_lowercase + string.digits + ' !@#$%^&*()_-+=:.,'
password_alphabet = string.ascii_lowercase + string.digits + ' !@#$%^&*()_-+=:.,'
# Do num tests.
# For each test, create a random data and random password, then
# encrypt and decrypt the data, compare the decrypted data to the
# original data to make sure that it matches.
import random
for i in range(num):
# Create random data between 64 and 512 characters in length.
dlen = random.randint(64, 512)
data = ''.join(random.choice(data_alphabet) for _ in range(dlen))
# Create a random password between 8 and 34 characters.
# Deliberately exceed the internal 32 character limit for
# some cases.
dlen = random.randint(8, 34)
password = ''.join(random.choice(password_alphabet) for _ in range(dlen))
# Encrypt and then decrypt.
aes = AESCipher(password)
encrypted = aes.encrypt(data)
decrypted = aes.decrypt(encrypted).decode('ascii')
# Compare to make sure that the decrypted value
# matches the original value.
if data != decrypted:
print('')
print('test02 - failed')
print('Password: {:>5} "{}"'.format(len(password), password))
print('Data : {:>5} "{}"'.format(len(data), data))
print('Dcrypted: {:>5} "{}"'.format(len(decrypted), decrypted))
assert data == decrypted
print('test02 - ok')
if __name__ == '__main__':
test01()
test02()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment