from Crypto import Random
from Crypto.Cipher import AES
import base64
from hashlib import md5
BLOCK_SIZE = 16
# https://blog.csdn.net/weixin_39912163/article/details/111422488
def pad(data):
length = BLOCK_SIZE - (len(data) % BLOCK_SIZE)
return data + (chr(length)*length).encode()
def unpad(data):
return data[:-(data[-1] if type(data[-1]) == int else ord(data[-1]))]
def bytes_to_key(data, salt, output=48):
# extended from https://gist.github.com/gsakkis/4546068
assert len(salt) == 8, len(salt)
data += salt
key = md5(data).digest()
final_key = key
while len(final_key) < output:
key = md5(key + data).digest()
final_key += key
return final_key[:output]
def encrypt(message, passphrase):
salt = Random.new().read(8)
key_iv = bytes_to_key(passphrase.encode(), salt, 32+16)
key = key_iv[:32]
iv = key_iv[32:]
aes = AES.new(key, AES.MODE_CBC, iv)
return base64.b64encode(b"Salted__" + salt + aes.encrypt(pad(message)))
def decrypt(encrypted, passphrase):
encrypted = base64.b64decode(encrypted)
assert encrypted[0:8] == b"Salted__"
salt = encrypted[8:16]
key_iv = bytes_to_key(passphrase.encode(), salt, 32+16)
key = key_iv[:32]
iv = key_iv[32:]
aes = AES.new(key, AES.MODE_CBC, iv)
return unpad(aes.decrypt(encrypted[16:]))
# password = "some password".encode()
# ct_b64 = "U2FsdGVkX1+ATH716DgsfPGjzmvhr+7+pzYfUzR+25u0D7Z5Lw04IJ+LmvPXJMpz"
# # ct_b64 = "U2FsdGVkX1+ATH716DgsfPGjzmvhr+7+pzYfUzR+25u0D7Z5Lw04IJ+LmvPXJMpz"
#
# pt = decrypt(ct_b64, password)
# print("pt", pt)
#
# print("pt", decrypt(encrypt(pt, password), password))
passphrase = "passphrase"
test = "U2FsdGVkX187CV++0s/Eoo6Y4O1mJqcbofVFvTfBU5g="
result = decrypt(test, passphrase).decode('utf-8')
print(result)
a = encrypt("hello world".encode(),passphrase)
print(a.decode())
result = decrypt(a, passphrase).decode('utf-8')
print(result)
import CryptoJS from 'crypto-js';
const KEY = 'passphrase'; // 此key需与后端一致
// 加密
function encrypt(data) {
const encrypt = CryptoJS.AES.encrypt(data, KEY)
return encrypt.toString();
}
// 解密
function decrypt(data) {
const decrypt = CryptoJS.AES.decrypt(data, KEY)
return decrypt.toString(CryptoJS.enc.Utf8);
}
export { encrypt, decrypt};