Skip to content

Instantly share code, notes, and snippets.

@crmccreary
Created May 20, 2013 02:17
Show Gist options
  • Star 52 You must be signed in to star a gist
  • Fork 13 You must be signed in to fork a gist
  • Save crmccreary/5610068 to your computer and use it in GitHub Desktop.
Save crmccreary/5610068 to your computer and use it in GitHub Desktop.
Encryption using pycrypto, AES, and PKCS5 padding
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[0:-ord(s[-1])]
class AESCipher:
def __init__( self, key ):
"""
Requires hex encoded param as a key
"""
self.key = key.decode("hex")
def encrypt( self, raw ):
"""
Returns hex encoded encrypted value!
"""
raw = pad(raw)
iv = Random.new().read(AES.block_size);
cipher = AES.new( self.key, AES.MODE_CBC, iv )
return ( iv + cipher.encrypt( raw ) ).encode("hex")
def decrypt( self, enc ):
"""
Requires hex encoded param to decrypt
"""
enc = enc.decode("hex")
iv = enc[:16]
enc= enc[16:]
cipher = AES.new(self.key, AES.MODE_CBC, iv )
return unpad(cipher.decrypt( enc))
if __name__== "__main__":
key = "140b41b22a29beb4061bda66b6747e14"
ciphertext = "4ca00ff4c898d61e1edbf1800618fb2828a226d160dad07883d04e008a7897ee2e4b7465d5290d0c0e6c6822236e1daafb94ffe0c5da05d9476be028ad7c1d81";
key=key[:32]
decryptor = AESCipher(key)
plaintext = decryptor.decrypt(ciphertext)
print "%s" % plaintext
@gkadillak
Copy link

To anybody else looking for this, the Crypto.Util.Padding.padis now in release 2.7a1. Here's the source: https://github.com/dlitz/pycrypto/blob/master/lib/Crypto/Util/Padding.py

@alastairmccormack
Copy link

PyCryptoDome, a Pycrypto fork, includes Crypto.Util.Padding.pad

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment