Created
November 11, 2014 15:43
-
-
Save notsobad/64ec8fdae52bd107dece to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import base64 | |
from Crypto.Cipher import AES | |
from Crypto import Random | |
BS = 16 | |
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS) | |
unpad = lambda s : s[:-ord(s[len(s)-1:])] | |
class AESCipher: | |
'''AES | |
>>> aes = AESCipher('N6pm5ykRJhoDlsJlPFEYjVgUk5PiZwpQ') | |
>>> msg = 'hello world' | |
>>> msg == aes.decrypt(aes.encrypt(msg)) | |
True | |
>>> msg = 'just a test :-)' | |
>>> msg == aes.decrypt(aes.encrypt(msg)) | |
True | |
''' | |
def __init__( self, key ): | |
self.key = key | |
def encrypt( self, raw ): | |
raw = pad(raw) | |
iv = Random.new().read( AES.block_size ) | |
cipher = AES.new( self.key, AES.MODE_CBC, iv ) | |
return base64.b64encode( iv + cipher.encrypt( raw ) ) | |
def decrypt( self, enc ): | |
enc = base64.b64decode(enc) | |
iv = enc[:16] | |
cipher = AES.new(self.key, AES.MODE_CBC, iv ) | |
return unpad(cipher.decrypt( enc[16:] )) | |
if __name__ == '__main__': | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment