python如何给文件加密与解密

25次阅读
没有评论

共计 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字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)