import base64
import binascii
import re
from Crypto.Cipher import AES
class AESCBC:
def __init__(self):
self.key = 'weg2452g&%$#ghsghf'.encode('utf-8') # Definition key value
self.mode = AES.MODE_CBC
self.bs = 16 # block size
self.PADDING = lambda s: s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs) # Insufficient 16 Long , Make up automatically , Complement rule : If you are short, you can make up for a few
# encryption
def encrypt(self, text):
iv = bytes(str(text), encoding='utf-8')[0:16] # Define dynamics IV
generator = AES.new(self.key, self.mode, iv)
crypt = generator.encrypt(self.PADDING(text).encode('utf-8'))
crypted_str = base64.urlsafe_b64encode(crypt) # Output Base64
# crypted_str = binascii.b2a_hex(crypt) # Output Hex
result = crypted_str.decode()
return result
# Decrypt
def decrypt(self, text, plain_text):
iv = bytes(str(plain_text), encoding='utf-8')[0:16]
generator = AES.new(self.key, self.mode, iv)
text += (len(text) % 4) * '='
decrpyt_bytes = base64.urlsafe_b64decode(text) # Output Base64
# decrpyt_bytes = binascii.a2b_hex(text) # Output Hex
meg = generator.decrypt(decrpyt_bytes)
# Remove illegal characters after decoding
try:
result = re.compile('[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f\n\r\t]').sub('', meg.decode())
except Exception:
result = ' Decoding failed , Please try again !'
return result
if __name__ == '__main__':
a = AESCBC()
# print(a.encrypt('1'))
# print(a.decrypt(a.encrypt('1')))
token_dict = {
"inviteeType": 1,
"invitee": "[email protected]",
"resourceType": 4,
"resourceId": 433,
"shareType": 7,
"expireAt": 1666253258
}
en_result = a.encrypt(str(token_dict))
print(en_result)
print("\n")
print(a.decrypt(en_result, token_dict))