Skip to content

Instantly share code, notes, and snippets.

@swinton
Last active November 8, 2024 18:31
Show Gist options
  • Save swinton/8409454 to your computer and use it in GitHub Desktop.
Save swinton/8409454 to your computer and use it in GitHub Desktop.
Encrypt & Decrypt using PyCrypto AES 256 From 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:-ord(s[-1])]
class AESCipher:
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:] ))
cipher = AESCipher('mysecretpassword')
encrypted = cipher.encrypt('Secret Message A')
decrypted = cipher.decrypt(encrypted)
print encrypted
print decrypted
@lroggendorff
Copy link

AWESOMESAUCE.

like a boss

@rvrheenen
Copy link

This only works because the 'mysecretpassword' is 16 bytes. If it were a different (not dividable by 16) amount of bytes you'd get
"ValueError: AES key must be either 16, 24, or 32 bytes long"
To avoid this the key may be hashed:
self.key = hashlib.sha256(key.encode('utf-8')).digest()

@mguezuraga
Copy link

Very minor changes to make it python 3 compatible https://gist.github.com/mguezuraga/257a662a51dcde53a267e838e4d387cd

@Craz1k0ek
Copy link

Craz1k0ek commented Dec 19, 2017

def pad(s):
    return s + (BS - len(s) % BS) * chr(BS - len(s) % BS)


def unpad(s):
    return s[0:-s[-1]]

lambda removed(pep 8 support)
ord removed(python 3 support)

@KorvinSilver
Copy link

KorvinSilver commented Jan 20, 2018

In Python 3 using the modifications of Craz1k0ek it still doesn't work with Unicode. For example the input Hello, 你好 raises ValueError: Input strings must be a multiple of 16 in length

Edit: found a working version: https://stackoverflow.com/a/44212550

@RichardEllicott
Copy link

i think this is aes 128, we have a standard blocksize of 16 bytes (128bit)

@RichardEllicott
Copy link

i can't seem to find how to do aes256

@vsantosh1986
Copy link

Please provide the JAVA code equivalent to above which is in python.

@martian0x80
Copy link

i think this is aes 128, we have a standard blocksize of 16 bytes (128bit)

Key size decides if it is aes 256 or 128, block size is 16 in both of em

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