以下是关于Python中用密钥压缩字典的相关信息:
以下是一个Python代码示例,展示了如何使用AES算法对字典中的键值对进行加密:
from Crypto.Cipher import AES
import base64
def encrypt_dict(data, key):
cipher = AES.new(key, AES.MODE_EAX)
ciphertext, tag = cipher.encrypt_and_digest(str(data).encode('utf-8'))
return {
'ciphertext': base64.b64encode(ciphertext).decode('utf-8'),
'tag': base64.b64encode(tag).decode('utf-8'),
'nonce': base64.b64encode(cipher.nonce).decode('utf-8')
}
def decrypt_dict(data, key):
ciphertext = base64.b64decode(data['ciphertext'])
tag = base64.b64decode(data['tag'])
nonce = base64.b64decode(data['nonce'])
cipher = AES.new(key, AES.MODE_EAX, nonce=nonce)
plaintext = cipher.decrypt_and_verify(ciphertext, tag)
return eval(plaintext.decode('utf-8'))
# 示例
data = {'name': 'Alice', 'age': 20, 'password': '123456'}
key = b'Sixteen byte key'
encrypted_data = encrypt_dict(data, key)
print(encrypted_data)
decrypted_data = decrypt_dict(encrypted_data, key)
print(decrypted_data)
在这个示例中,我们使用了Python中的Crypto库,对字典中的键值对进行了AES加密和解密。用户可以根据自己的需求选择合适的加密算法和密钥长度,以保护敏感信息的安全性。
领取专属 10元无门槛券
手把手带您无忧上云