首页主机资讯python文本文件加密的方法是什么

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

时间2024-05-28 16:10:04发布访客分类主机资讯浏览887
导读:Python中可以使用加密算法来对文本文件进行加密。常用的加密算法包括AES、DES、RSA等。以下是使用AES加密算法对文本文件进行加密和解密的示例代码: from Crypto.Cipher import AES from Crypto...

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文件中。需要注意的是,加密和解密时需要使用相同的密钥。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: python文本文件加密的方法是什么
本文地址: https://pptw.com/jishu/670018.html
maven仓库配置失败的原因有哪些 hadoop集群怎么搭建及配置

游客 回复需填写必要信息