Skip to content

Instantly share code, notes, and snippets.

@glowinthedark
Forked from pfote/AesCrypt.py
Last active August 2, 2020 11:57
Show Gist options
  • Save glowinthedark/ef89be8eca9f5abf09147fcf8d061758 to your computer and use it in GitHub Desktop.
Save glowinthedark/ef89be8eca9f5abf09147fcf8d061758 to your computer and use it in GitHub Desktop.
AES256 with PKCS5 padding
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from Crypto.Cipher import AES
import base64
import re
class AesCbc:
def __init__(self, key=None):
self.key = key
self.mode = AES.MODE_CBC
self.size = AES.block_size
self.pad = lambda s: s + (self.size - len(s) % self.size) * chr(self.size - len(s) % self.size)
def encrypt(self, content):
cryptor = AES.new(self.key.encode("utf8"), self.mode, bytearray(16))
encrypted = cryptor.encrypt(self.pad(content))
return base64.urlsafe_b64encode(encrypted)
def decrypt(self, content):
cryptor = AES.new(self.key.encode("utf8"), self.mode, bytearray(16))
content += (len(content) % 4) * '='
content = base64.urlsafe_b64decode(content)
decrypted = cryptor.decrypt(content)
try:
return re.compile('[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f\n\r\t]').sub('', decrypted.decode())
except Exception:
raise ValueError("inputted value can not be decrypted.")
if __name__ == '__main__':
aes = AesCbc(key="aaaaaaaaaaaaaaaaaaaaaaaaaaa")
dec = aes.decrypt("0M9V6FvjopSNbUQcV3uv68DhB5/ZubczlbsNqn9bM98=")
print(dec)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment