Created
March 6, 2019 15:48
-
-
Save nantsou/dcbddefd8a307dbac49568e036f9357d to your computer and use it in GitHub Desktop.
AES/CBC/PKCS5PADDING in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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.") |
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
I have found the solution that work perfectly for me:
Code Reference : https://yococoxc.github.io/15493867450071.html