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

python如何給文件加密與解密

138次閱讀
沒有評論

共計 1104 個字符,預計需要花費 3 分鐘才能閱讀完成。

要給文件加密和解密,可以使用 Python 中的加密模塊如 cryptographyPyCrypto。以下是一個使用 PyCrypto 模塊進行文件加密和解密的示例代碼:

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

def encrypt_file(input_file, output_file, key):
    cipher = AES.new(key, AES.MODE_EAX)
    with open(input_file, 'rb') as f_in:
        data = f_in.read()
        nonce = cipher.nonce
        ciphertext, tag = cipher.encrypt_and_digest(data)
    
    with open(output_file, 'wb') as f_out:
        f_out.write(nonce)
        f_out.write(tag)
        f_out.write(ciphertext)

def decrypt_file(input_file, output_file, key):
    with open(input_file, 'rb') as f_in:
        nonce = f_in.read(16)
        tag = f_in.read(16)
        ciphertext = f_in.read()
    
    cipher = AES.new(key, AES.MODE_EAX, nonce=nonce)
    data = cipher.decrypt_and_verify(ciphertext, tag)
    
    with open(output_file, 'wb') as f_out:
        f_out.write(data)

# Generate a random key
key = get_random_bytes(16)

# Encrypt a file
encrypt_file('input.txt', 'encrypted.txt', key)

# Decrypt the encrypted file
decrypt_file('encrypted.txt', 'output.txt', key)

在上面的示例中,我們首先使用 encrypt_file() 函數對輸入文件進行加密,然后使用 decrypt_file() 函數對加密后的文件進行解密。在加密和解密過程中,我們使用 AES 加密算法和隨機生成的 16 字節密鑰。

請注意,加密和解密文件時,務必保管好密鑰,以便正確解密文件。

丸趣 TV 網 – 提供最優質的資源集合!

正文完
 
丸趣
版權聲明:本站原創文章,由 丸趣 2024-03-19發表,共計1104字。
轉載說明:除特殊說明外本站除技術相關以外文章皆由網絡搜集發布,轉載請注明出處。
評論(沒有評論)
主站蜘蛛池模板: 孟连| 景东| 邢台市| 巫山县| 文昌市| 天台县| 建湖县| 邛崃市| 新丰县| 珲春市| 石楼县| 宁都县| 太谷县| 丘北县| 杨浦区| 乐都县| 长丰县| 金塔县| 湖北省| 大城县| 荆门市| 甘泉县| 辽源市| 仙桃市| 长白| 大庆市| 临泉县| 招远市| 潼关县| 武山县| 隆德县| 沭阳县| 镶黄旗| 五常市| 莫力| 马山县| 湖北省| 巴里| 溧水县| 泽普县| 新密市|