Skip to content

Instantly share code, notes, and snippets.

@noperator
Last active June 14, 2020 01:39
Show Gist options
  • Save noperator/7285a4d0f98b1da19d7f6013ddb64baa to your computer and use it in GitHub Desktop.
Save noperator/7285a4d0f98b1da19d7f6013ddb64baa to your computer and use it in GitHub Desktop.
AES-CBC cryptor implemented in Python.
#!/usr/bin/env python3
'''
Install dependencies:
$ python3 -m venv env
$ source env/bin/activate
$ python3 -m pip install -U pip pycryptodome
Usage:
$ python3 aes_cryptor.py e web.config
qhoLTUH0ah0tz6a2MFvXPQ%3D%3D
$ python3 aes_cryptor.py d qhoLTUH0ah0tz6a2MFvXPQ%3D%3D
web.config
'''
from base64 import b64encode, b64decode
from sys import argv
from urllib.parse import quote, unquote
from Crypto.Cipher import AES
key = bytes(range(32))
mode = AES.MODE_CBC
iv = bytes(range(16))
cryptor = AES.new(key, mode, IV=iv)
action = argv[1] # Pass "e" to encrypt, or "d" to decrypt.
# Encrypt a plaintext string.
if action == 'e':
plain = str(argv[2]).encode()
pad_len = 16 - (len(plain) % 16)
plain += bytes([pad_len]) * pad_len
cipher = cryptor.encrypt(plain)
cipher_b64 = b64encode(cipher).decode()
cipher_b64_url = quote(cipher_b64)
print(cipher_b64_url)
# Decrypt a Base64- and percent-encoded ciphertext string.
elif action == 'd':
cipher_b64_url = str(argv[2])
cipher_b64 = unquote(cipher_b64_url).encode()
cipher = b64decode(cipher_b64)
plain = cryptor.decrypt(cipher).decode()
print(plain)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment