Skip to content

Instantly share code, notes, and snippets.

@nantsou
Created March 6, 2019 15:48
Show Gist options
  • Save nantsou/dcbddefd8a307dbac49568e036f9357d to your computer and use it in GitHub Desktop.
Save nantsou/dcbddefd8a307dbac49568e036f9357d to your computer and use it in GitHub Desktop.
AES/CBC/PKCS5PADDING in python
# -*- coding: utf-8 -*-
from Crypto.Cipher import AES
import base64
import re
DEFAULT_KEY = 'anrxvpAAa9x5kEUm'
class AesCbc:
def __init__(self, key=None):
self.key = key or DEFAULT_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, self.mode, self.key)
encrypted = cryptor.encrypt(self.pad(content))
return base64.urlsafe_b64encode(encrypted)
def decrypt(self, content):
cryptor = AES.new(self.key, self.mode, self.key)
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.")
@nantsou
Copy link
Author

nantsou commented Jan 12, 2020

Thank you for the information.
I haven’t gotten the chance to check the codes.

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