fromCryptoimportRandomfromCrypto.CipherimportAESimportbase64fromhashlibimportmd5BLOCK_SIZE=16#https://blog.csdn.net/weixin_39912163/article/details/111422488defpad(data):length=BLOCK_SIZE-(len(data)%BLOCK_SIZE)复制代码返回数据+(chr(length)*length).encode()defunpad(data):returndata[:-(data[-1]iftype(data[-1])==intelseord(data[-1]))]defbytes_to_key(data,salt,output=48):#扩展自https://gist.github.com/gsakkis/4546068assertlen(salt)==8,len(salt)data+=saltkey=md5(data).digest()final_key=keywhilelen(final_key)<输出:key=md5(key+data).digest()final_key+=keyreturnfinal_key[:output]defencrypt(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)返回base64.b64encode(b"Salted__"+salt+aes.encrypt(pad(message)))defdecrypt(encrypted,passphrase):encrypted=base64.b64decode(encrypted)assertencrypted[0:8]==b"Salted__"salt=encrypted[8:16]key_iv=bytes_to_key(passphrase.encode(),盐,32+16)key=key_iv[:32]iv=key_iv[32:]aes=AES.new(key,AES.MODE_CBC,iv)returnunpad(aes.decrypt(encrypted[16:]))#password="somepassword".encode()#ct_b64="U2FsdGVkX1+ATH716DgsfPGjzmvhr+7+pzYfUzR+25u0D7Z5Lw04IJ+LmvPXJMpz"##ct_b64="U2FsdGVkX1+ATH716DgsfPGjzmvhr+7+pzYfUzR+25u0D7Z5Lw04IJ+LmvPXJMpz"##pt=解密(ct_b64,密码)#打印(“pt”,pt)##打印(“pt”,解密(加密(pt,密码),密码))密码=“密码”测试=“U2FsdGVkX187CV++0s/Eoo6Y4O1mJqcbofVFvTfBU5g="result=decrypt(test,passphrase).decode('utf-8')print(result)a=encrypt("helloworld".encode(),passphrase)print(a.decode())result=decrypt(a,passphrase).decode('utf-8')print(result)从'crypto-js'导入CryptoJS;constKEY='passphr阿瑟';//这个key需要和后端保持一致//加密函数encrypt(data){constencrypt=CryptoJS.AES.encrypt(data,KEY)returnencrypt.toString();}//解密函数decrypt(data){constdecrypt=CryptoJS.AES.decrypt(data,KEY)returndecrypt.toString(CryptoJS.enc.Utf8);}export{加密,解密};
