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)