$ pip install pycryptodome $ pip install pycryptodomex
$ vim settings.py
#AES cipher
try:
from .aes_key import *
except ImportError:
AES_KEY='oDZC5a6rhyukFmKCbPS6M45TFROLmrlB'
$ vim aes_key.py
AES_KEY='dMchLlLllvrDtQUxXDLpAWr2v1EdjuLU'
$ python manage.py shell
from project.settings import *
print(AES_KEY)
import base64
import hashlib
from Crypto import Random
from Crypto.Cipher import AES
from Crypto.Util import Padding
class AESCipher(object):
def __init__(self, key):
self.key = (hashlib.md5(key.encode('utf-8')).hexdigest()).encode('utf-8')
def encrypt(self, raw):
iv = Random.get_random_bytes(AES.block_size)
cipher = AES.new(self.key, AES.MODE_CBC, iv)
data = Padding.pad(raw.encode('utf-8'), AES.block_size, 'pkcs7')
return base64.b64encode(iv + cipher.encrypt(data)).decode('utf-8')
def decrypt(self, enc):
enc = base64.b64decode(enc.encode('utf-8'))
iv = enc[:AES.block_size]
cipher = AES.new(self.key, AES.MODE_CBC, iv)
data = Padding.unpad(cipher.decrypt(enc[AES.block_size:]), AES.block_size, 'pkcs7')
return data.decode('utf-8')
import random
import string
from project.lib.cipher import AESCipher
raw_text = 'Hello'
key = 'y6lLepZQpppdzjkeG5MhUaaaRCychpDd'
print('key:' + key)
cipher = AESCipher(key)
encrypted_text = cipher.encrypt(raw_text)
print(encrypted_text)
decrypted_text = cipher.decrypt(encrypted_text)
print(decrypted_text)
Recommended Posts