久久精品人人爽,华人av在线,亚洲性视频网站,欧美专区一二三

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

186次閱讀
沒有評論

共計 902 個字符,預(yù)計需要花費 3 分鐘才能閱讀完成。

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

丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!

正文完
 
丸趣
版權(quán)聲明:本站原創(chuàng)文章,由 丸趣 2024-04-16發(fā)表,共計902字。
轉(zhuǎn)載說明:除特殊說明外本站除技術(shù)相關(guān)以外文章皆由網(wǎng)絡(luò)搜集發(fā)布,轉(zhuǎn)載請注明出處。
評論(沒有評論)
主站蜘蛛池模板: 章丘市| 库尔勒市| 蓬溪县| 新源县| 涟水县| 揭西县| 绥阳县| 德江县| 临桂县| 石景山区| 图木舒克市| 牡丹江市| 乌鲁木齐市| 驻马店市| 东光县| 治县。| 临汾市| 民丰县| 怀远县| 江门市| 长武县| 广宗县| 新密市| 安丘市| 思南县| 来宾市| 普格县| 天峨县| 遂平县| 鞍山市| 武平县| 宁陵县| 岱山县| 石台县| 延庆县| 白玉县| 奉化市| 宜兰县| 青岛市| 都兰县| 西华县|