Skip to content

Instantly share code, notes, and snippets.

@frizz925
Last active May 28, 2024 02:47
Show Gist options
  • Save frizz925/ac0fb026314807959db5685ac149ed67 to your computer and use it in GitHub Desktop.
Save frizz925/ac0fb026314807959db5685ac149ed67 to your computer and use it in GitHub Desktop.
AES-256-CBC w/ Base64 using PyCryptodome library
from Crypto.Cipher import AES
from Crypto.Util import Padding
from hashlib import md5
from base64 import b64encode, b64decode
import sys
passphrase = sys.argv[1]
content = sys.argv[2]
print(passphrase, content)
mode = AES.MODE_CBC
bs = AES.block_size
# encrypting
key = md5(passphrase.encode('utf-8')).hexdigest().encode('utf-8')
body = Padding.pad(content.encode('utf-8'), bs)
iv = key[8:bs+8]
cipher = AES.new(key, mode, iv)
key = b64encode(key).decode('utf-8')
body = b64encode(cipher.encrypt(body)).decode('utf-8')
iv = b64encode(iv).decode('utf-8')
result = "%s.%s.%s" % (key, body, iv)
print(result)
# decrypting
key, body, iv = result.split(".")
key = b64decode(key.encode('utf-8'))
body = b64decode(body.encode('utf-8'))
iv = b64decode(iv.encode('utf-8'))
cipher = AES.new(key, mode, iv)
body = Padding.unpad(cipher.decrypt(body), bs).decode('utf-8')
print(body)
@mcorbridge
Copy link

Thank you! It was a struggle trying to find a simple example that worked. Yours was perfect.

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