共計 936 個字符,預計需要花費 3 分鐘才能閱讀完成。
在 Python 中,可以使用各種算法對數據進行加密。以下是使用 AES 算法對數據進行加密和解密的示例代碼:
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
def encrypt_data(data, key):
cipher = AES.new(key, AES.MODE_EAX)
nonce = cipher.nonce
ciphertext, tag = cipher.encrypt_and_digest(data)
return nonce + ciphertext + tag
def decrypt_data(encrypted_data, key):
nonce = encrypted_data[:16]
ciphertext = encrypted_data[16:-16]
tag = encrypted_data[-16:]
cipher = AES.new(key, AES.MODE_EAX, nonce)
decrypted_data = cipher.decrypt_and_verify(ciphertext, tag)
return decrypted_data
# 隨機生成 16 字節的密鑰
key = get_random_bytes(16)
# 要加密的數據
data = b"Hello, World!"
# 加密數據
encrypted_data = encrypt_data(data, key)
print(" 加密后的數據:", encrypted_data)
# 解密數據
decrypted_data = decrypt_data(encrypted_data, key)
print(" 解密后的數據:", decrypted_data.decode())
請注意,這個例子使用了 Crypto
模塊,它需要安裝 pycryptodome
庫。你可以使用 pip
命令安裝它:
pip install pycryptodome
此代碼使用 AES 算法使用 16 字節的密鑰對數據進行加密和解密。加密后的數據包括一個 16 字節的隨機生成的 nonce,加密的數據本身,以及一個 16 字節的 tag,用于驗證數據的完整性。在解密時,需要使用相同的密鑰和 nonce 來解密數據并驗證 tag。
丸趣 TV 網 – 提供最優質的資源集合!
正文完