要实现本地存储值的加密和解密,您可以使用加密算法来对值进行加密,并使用相同的算法和密钥进行解密。以下是一个使用AES算法进行加密和解密的示例代码:
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from base64 import b64encode, b64decode
def encrypt(plaintext, key):
cipher = AES.new(key, AES.MODE_CBC)
ciphertext = cipher.encrypt(pad(plaintext.encode(), AES.block_size))
iv = b64encode(cipher.iv).decode('utf-8')
ciphertext = b64encode(ciphertext).decode('utf-8')
return iv + ciphertext
def decrypt(ciphertext, key):
iv = b64decode(ciphertext[:24])
ciphertext = b64decode(ciphertext[24:])
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = unpad(cipher.decrypt(ciphertext), AES.block_size)
return plaintext.decode('utf-8')
# 示例使用
key = b'This is a 16 byte key'
plaintext = 'Hello, World!'
encrypted_text = encrypt(plaintext, key)
print('Encrypted:', encrypted_text)
decrypted_text = decrypt(encrypted_text, key)
print('Decrypted:', decrypted_text)
请注意,示例代码使用了Crypto
库中的AES算法。在运行代码之前,您需要安装pycryptodome
库。可以使用以下命令进行安装:
pip install pycryptodome
在示例代码中,encrypt
函数接受明文和密钥作为输入,并返回加密后的文本。decrypt
函数接受密文和密钥作为输入,并返回解密后的文本。
在示例中,密钥是一个16字节的字节数组。要确保密钥的安全性,可以使用更强大的密钥生成算法。此外,还可以使用其他加密算法,如DES、RSA等。但是,无论使用哪种算法,都需要妥善保管密钥以确保数据的安全性。