以下是一些优秀的Python库,用于不同类型文件加密,并包含代码示例:
对称加密:
from Crypto.Cipher import AES
def encrypt_file_symmetric(key, in_filename, out_filename=None, chunksize=64*1024):
if not out_filename:
out_filename = in_filename + ".enc"
encryptor = AES.new(key, AES.MODE_EAX)
with open(in_filename, 'rb') as infile:
with open(out_filename, 'wb') as outfile:
outfile.write(encryptor.nonce)
chunk = infile.read(chunksize)
while len(chunk) > 0:
encrypted_chunk = encryptor.encrypt(chunk)
outfile.write(encrypted_chunk)
chunk = infile.read(chunksize)
def decrypt_file_symmetric(key, in_filename, out_filename=None, chunksize=64*1024):
if not out_filename:
out_filename = in_filename[:-4]
with open(in_filename, 'rb') as infile:
nonce = infile.read(16)
decryptor = AES.new(key, AES.MODE_EAX, nonce)
with open(out_filename, 'wb') as outfile:
chunk = infile.read(chunksize)
while len(chunk) > 0:
decrypted_chunk = decryptor.decrypt(chunk)
outfile.write(decrypted_chunk)
chunk = infile.read(chunksize)
非对称加密:
from cryptography.fernet import Fernet
def generate_key():
key = Fernet.generate_key()
with open("key.txt", 'wb') as key_file:
key_file.write(key)
def encrypt_file_asymmetric(public_key_file, in_filename, out_filename=None, chunksize=64*1024):
if not out_filename:
out_filename = in_filename + ".enc"
with open(public_key_file, 'rb') as key_file:
public_key = key_file.read()
key = Fernet(public_key)
with open(in_filename, 'rb') as infile:
with open(out_filename, 'wb') as outfile:
chunk = infile.read(chunksize)
while len(chunk) > 0:
encrypted_chunk = key.encrypt(chunk)
outfile.write(encrypted_chunk)
chunk = infile.read(chunksize)
def decrypt_file_asymmetric(private_key_file, in_filename, out_filename=None, chunksize=64*1024):
if not out_filename:
out_filename = in_filename[:-4]
with open(private_key_file, 'rb') as key_file:
private_key = key_file.read()
key = Fernet(private_key)
with open(in_filename, 'rb') as infile:
chunk = infile.read(chunksize)
with open(out_filename, 'wb') as outfile:
while len(chunk) > 0:
decrypted_chunk = key.decrypt(chunk)
outfile.write(decrypted_chunk)
chunk = infile.read(chunksize)
文件压缩和加密:
import pyminizip
def compress_encrypt_file(in_filename, out_filename, password):
pyminizip.compress(in_filename, None, out_filename, password, 5)
def decompress_decrypt_file(in_filename, out_filename, password):
pyminizip.uncompress(in_filename, password, ".", out_filename)
这些库提供了不同类型文件加密的解决方案,可以根据需求选择适合的库和算法进行文件加密和解密操作。
上一篇:不同类型图形绘制所需时间的差异
下一篇:不同类型形状的数组数组