溫馨提示×

python文本文件加密的方法是什么

小億
157
2024-04-15 09:47:06
欄目: 編程語言

Python中可以使用加密算法來對文本文件進行加密。常用的加密算法包括AES、DES、RSA等。以下是使用AES加密算法對文本文件進行加密和解密的示例代碼:

from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes

# 生成隨機密鑰
key = get_random_bytes(16)

# 初始化AES加密器
cipher = AES.new(key, AES.MODE_EAX)

# 加密文本文件
with open('plaintext.txt', 'rb') as f:
    plaintext = f.read()
    ciphertext, tag = cipher.encrypt_and_digest(plaintext)

with open('encrypted.txt', 'wb') as f:
    f.write(cipher.nonce)
    f.write(tag)
    f.write(ciphertext)

# 解密文本文件
with open('encrypted.txt', 'rb') as f:
    nonce = f.read(16)
    tag = f.read(16)
    ciphertext = f.read()

cipher = AES.new(key, AES.MODE_EAX, nonce)
plaintext = cipher.decrypt(ciphertext)

try:
    cipher.verify(tag)
    with open('decrypted.txt', 'wb') as f:
        f.write(plaintext)
except ValueError:
    print("Decryption failed")

在上述代碼中,首先生成一個隨機密鑰,然后使用AES加密器對文本文件進行加密并保存到encrypted.txt文件中。接著讀取加密文件,解密并保存到decrypted.txt文件中。需要注意的是,加密和解密時需要使用相同的密鑰。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女