Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Encrypt & Decrypt using PyCrypto AES 256From http://stackoverflow.com/a/12525165/119849
#!/usr/bin/env python
import base64
from Crypto import Random
from Crypto.Cipher import AES
BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[0:-s[-1]]
class AESCipher:
def __init__( self, key ):
self.key = hashlib.sha256(key.encode('utf-8')).digest()
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:] ))
cipher = AESCipher('mysecretpassword')
encrypted = cipher.encrypt('Secret Message A')
decrypted = cipher.decrypt(encrypted)
print(encrypted)
print(decrypted)
pycrypto==2.6.1
@zcking

This comment has been minimized.

Copy link

@zcking zcking commented Jun 13, 2018

You forgot to import hashlib at the top of the script.

@anistark

This comment has been minimized.

Copy link

@anistark anistark commented Aug 26, 2018

Added import hashlib.

Still, I'm getting:
Object type <class 'str'> cannot be passed to C code.

@javaking2013

This comment has been minimized.

Copy link

@javaking2013 javaking2013 commented Oct 4, 2018

Added import hashlib.

Still, I'm getting:
Object type <class 'str'> cannot be passed to C code.

You have to pass in byte array and not string. Use this on line 22:

return base64.b64encode( iv + cipher.encrypt( raw.encode('utf8') ) )

@Lishenga

This comment has been minimized.

Copy link

@Lishenga Lishenga commented Nov 20, 2018

when i try to decrypt the encrypted output, i dont get the input i passed into the encrypt function, what is the issue?
Am using pycryptodome

@shaliuno

This comment has been minimized.

Copy link

@shaliuno shaliuno commented Jan 31, 2020

Finally something, that works out of box!

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