Python 加密和解密可以用于保護數(shù)據(jù)的隱私和安全。常見的加密和解密方法有:
以下是一個簡單的 AES 加密和解密示例:
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
import base64
# 加密函數(shù)
def encrypt(data, key):
cipher = AES.new(key, AES.MODE_CBC)
ct_bytes = cipher.encrypt(pad(data.encode('utf-8'), AES.block_size))
iv = base64.b64encode(cipher.iv).decode('utf-8')
ct = base64.b64encode(ct_bytes).decode('utf-8')
return iv + ':' + ct
# 解密函數(shù)
def decrypt(encrypted_data, key):
iv, ct = encrypted_data.split(':')
iv = base64.b64decode(iv)
ct = base64.b64decode(ct)
cipher = AES.new(key, AES.MODE_CBC, iv)
return unpad(cipher.decrypt(ct), AES.block_size).decode('utf-8')
# 示例
key = get_random_bytes(16) # 生成一個隨機的 AES 密鑰
data = 'Hello, World!'
encrypted_data = encrypt(data, key)
print('加密后的數(shù)據(jù):', encrypted_data)
decrypted_data = decrypt(encrypted_data, key)
print('解密后的數(shù)據(jù):', decrypted_data)
請注意,這個示例需要安裝 pycryptodome
庫??梢允褂靡韵旅畎惭b:
pip install pycryptodome