Skip to content

CryptoZip 类和压缩加密示例

本文档介绍了一个用于加密文件并将其压缩成ZIP文件的Python类 CryptoZip。这个类使用了 pyminizip 库进行文件压缩和加密。

This document introduces a Python class CryptoZip for encrypting files and compressing them into ZIP files. The class uses the pyminizip library for compression and encryption.

前置条件 (Prerequisites)

在运行该代码之前,需要安装 pyminizip 库,可以使用以下命令进行安装:

Before running the code, you need to install the pyminizip library. You can install it using the following command:

bash
pip install pyminizip

代码详解 (Code Explanation)

CryptoZip 类 (CryptoZip Class)

CryptoZip 类的主要功能是将文件内容写入临时文件,并将其压缩成加密的ZIP文件。

The main function of the CryptoZip class is to write file content to a temporary file and compress it into an encrypted ZIP file.

python
import pyminizip
from io import BytesIO
from base64 import b64encode
import os
import uuid
import shutil

class CryptoZip:
    def __init__(self, password):
        self.password = password

    def compress_content_as_zip(self, plaintext_name, file_content, crypto_name):
        unique_id = uuid.uuid4().hex
        os.makedirs(unique_id, exist_ok=True)

        crypto_name    = unique_id + '/' + crypto_name
        plaintext_name = unique_id + '/' + plaintext_name

        # Write the content to a temporary file
        with open(plaintext_name, 'wb') as temp_file:
            temp_file.write(file_content)
        
        # Compress the temporary file into an encrypted zip file
        pyminizip.compress(plaintext_name, None, crypto_name, self.password, 5)
        
        # Read the encrypted zip file into a BytesIO object
        encrypted_zip_io = BytesIO()
        with open(crypto_name, 'rb') as encrypted_file:
            encrypted_zip_io.write(encrypted_file.read())
        
        # Clean up the temporary files
        shutil.rmtree(unique_id)
        
        encrypted_zip_io.seek(0)
        return encrypted_zip_io

init 方法 (Method)

初始化 CryptoZip 类的实例,接受一个参数 password 作为ZIP文件的加密密码。

Initializes an instance of the CryptoZip class, accepting a parameter password as the encryption password for the ZIP file.

compress_content_as_zip 方法 (Method)

将文件内容写入一个临时文件,并将其压缩成加密的ZIP文件,最终返回一个包含加密ZIP文件内容的 BytesIO 对象。

Writes the file content to a temporary file and compresses it into an encrypted ZIP file, eventually returning a BytesIO object containing the encrypted ZIP file content.

参数 (Parameters):

  • plaintext_name:临时文件的名称 (Name of the temporary file)。
  • file_content:要写入临时文件的内容 (Content to be written to the temporary file)。
  • crypto_name:生成的加密ZIP文件的名称 (Name of the generated encrypted ZIP file)。

main 函数 (Main Function)

展示了如何使用 CryptoZip 类进行文件加密和压缩的示例。

Shows an example of how to use the CryptoZip class for file encryption and compression.

python
def main():
    PASSWORD = "test"

    filename = "example"
    plaintext_name = f'{filename}.txt'
    crypto_name    = f'{filename}.zip'

    file_content = b"example content"

    crypto_zip = CryptoZip(PASSWORD)
    zip_file = crypto_zip.compress_content_as_zip(plaintext_name, file_content, crypto_name)
    zip_file_bytes = zip_file.getvalue()
    print(len(zip_file_bytes))
    print(zip_file_bytes)

if __name__ == "__main__":
    main()

示例详解 (Example Explanation)

  1. 设置密码 PASSWORD (Set password PASSWORD)。
  2. 定义文件名 filename、明文文件名 plaintext_name 和加密ZIP文件名 crypto_name (Define file name filename, plaintext file name plaintext_name, and encrypted ZIP file name crypto_name)。
  3. 设置文件内容 file_content (Set file content file_content)。
  4. 创建 CryptoZip 类的实例 crypto_zip (Create an instance of the CryptoZip class crypto_zip)。
  5. 调用 compress_content_as_zip 方法进行文件加密和压缩,并获取ZIP文件的字节内容 zip_file_bytes (Call the compress_content_as_zip method to encrypt and compress the file, and get the byte content of the ZIP file zip_file_bytes)。
  6. 打印ZIP文件的字节长度和内容 (Print the byte length and content of the ZIP file)。

通过上述代码,您可以将任意文件内容加密并压缩成ZIP文件,同时获取ZIP文件的字节流内容。

With the above code, you can encrypt and compress any file content into a ZIP file, and also get the byte stream content of the ZIP file.

Released under the MIT License.