从百度搜刮的代码,能用!!!
[Python] 纯文本查看 复制代码 from Crypto import Random
from Crypto.Cipher import AES
import base64
from hashlib import md5
def pad(data):
length = 16 - (len(data) % 16)
return data.encode(encoding='utf-8') + (chr(length)*length).encode(encoding='utf-8')
def unpad(data):
return data[:-(data[-1] if type(data[-1]) == int else ord(data[-1]))]
def bytes_to_key(data, salt, output=48):
data=data.encode(encoding='utf-8')
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, 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, 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:]))
if __name__ == '__main__':
# 加密
key = 'A1b2C3d4E5f6G7h8I9j0K!#'
data = '{"address":"0x32185387A611F9C49F90f99b61e37B39c3B1E4E1","projectId":"0x307832356562396465383466363163346362343462373431343034316561666637383836393861633534633565623436313835393166663931303665353130303065"}'
encrypt_data = encrypt(data, key)
print(encrypt_data)
# 解密
encrypt_data = 'U2FsdGVkX1+Go0Z4GVGrZftuTEh/nrzrBm6Gu9S4T9x6u9OPINhm8vmG7ezeNUgpNn2PzADjZHHXB1NWWMX9q+C+BaYD++XWvfyO4d9ccwM4H7IehwMR0DQWmxx3S9ShqxOW+fWCLlB9Jo/GQAV+7b7IkehGfiIwPNr+FzxnTrgPqivf/6E0+uqJl11BRs6Uc9/9KjneT2pFxJxBOBPsWJs1qhcjRzXWfjEKa+GXTO1kovYKw1i4T/o8TeULym0sWu2xD/9gQFhANEOX9o8elLEso+SRbdfG7nM7sbBVvhU='
decrypt_data = decrypt(encrypt_data, key)
print(decrypt_data)
|