cryptography与zlib系列:数据压缩与加密

cryptography与zlib系列:数据压缩与加密

这里采用对称加密方法进行加密,首先创建一个Fernet加密器,这里的key,通过密钥派生函数与设定的密码进行创建,具有更强的保密功能。

创建Fernet加密器函数

import os
from base64 import urlsafe_b64encode
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC


def get_cipher_suite(
    password: str,
    length,
    iterations: int = 480000,
) -> bytes:
    salt = os.urandom(16)  # 生成一个16字节的随机盐值
    # 创建密钥派生函数(KDF)
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),  # 使用SHA-256哈希算法
        length=32,  # 派生密钥的长度为32字节
        salt=salt,  # 使用盐值
        iterations=480000  # 迭代次数为480000
    )
    # 记录key的值,以便后续解密时使用
    key = urlsafe_b64encode(kdf.derive(password))  
    print(f"==>> key: {key}")
    cipher_suite = Fernet(key)

    return cipher_suite

获取压缩与加密后的数据

import zlib

def get_compress_encrypt_data(
    file_path: str,
    cipher_suite,
    compress_level: int = 9,
) -> bytes:
    with open(file_path, "rb") as f:
        data = f.read()
        compressed_data = zlib.compress(data, compress_level)
        encrypted_data = cipher_suite.encrypt(compressed_data)
        return encrypted_data

完整示例

import os
import zlib
from base64 import urlsafe_b64encode
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC


def get_cipher_suite(
    password: str,
    length: int,
    iterations: int = 480000,
) -> bytes:
    salt = os.urandom(16)  # 生成一个16字节的随机盐值
    # 创建密钥派生函数(KDF)
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),  # 使用SHA-256哈希算法
        length=32,  # 派生密钥的长度为32字节
        salt=salt,  # 使用盐值
        iterations=480000  # 迭代次数为480000
    )
    # 记录key的值,以便后续解密时使用
    key = urlsafe_b64encode(kdf.derive(password))  
    print(f"==>> key: {key}")
    cipher_suite = Fernet(key)

    return cipher_suite


def get_compress_encrypt_data(
    file_path: str,
    cipher_suite,
    compress_level: int = 9,
) -> bytes:
    with open(file_path, "rb") as f:
        data = f.read()
        compressed_data = zlib.compress(data, compress_level)
        encrypted_data = cipher_suite.encrypt(compressed_data)
        return encrypted_data


if __name__ == "__main__":
    from time import time

    start_time = time()
    password = "password"
    file_path = "test.txt"
    cipher_suite = get_cipher_suite(password, 32)
    encrypted_data = get_compress_encrypt_data(file_path, cipher_suite)
    end_time = time()
    print(f"Time taken: {end_time - start_time} seconds")
    file_encrypted_path = "test_encrypted.txt"
    with open(file_encrypted_path, "wb") as f:
        f.write(encrypted_data)
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值