该简易文件加密工具的核心是使用aes对称加密算法结合pbkdf2密钥派生实现文件的加密与解密,1.首先通过用户密码和随机salt使用pbkdf2-sha256生成256位密钥,2.加密时生成随机iv并采用aes-128-cbc模式对文件分块加密,3.将salt、iv和密文依次写入输出文件,4.解密时从文件读取salt和iv,用相同密码派生密钥后解密数据,5.通过pkcs#7填充确保块对齐并在解密后处理填充,整个流程保证了基本安全性,适用于学习或低敏感场景,最终实现一个结构完整、易于理解的加密工具。

做一款简易文件加密工具,核心是实现基本的加密算法,让用户能对文件进行加密和解密操作。这类工具适合学习用途或对安全性要求不高的场景。下面介绍一种简单可行的实现方案,包含基本加密算法选择、流程设计和代码思路。
对于简易工具,推荐使用对称加密算法,因为加解密使用同一个密钥,实现简单、速度快。
常用且安全的对称算法有:
建议:使用AES-128-CBC 或 AES-256-GCM 模式,平衡安全性和实现难度。
一个基本的文件加密流程如下:
import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives import hashes
import hashlib
def derive_key(password: str, salt: bytes) -> bytes:
"""从密码和salt生成256位密钥"""
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=100000,
)
key = kdf.derive(password.encode())
return key
def encrypt_file(input_path: str, output_path: str, password: str):
# 生成随机salt和IV
salt = os.urandom(16)
iv = os.urandom(16)
# 生成密钥
key = derive_key(password, salt)
# 初始化AES加密器
cipher = Cipher(algorithms.AES(key), modes.CBC(iv))
encryptor = cipher.encryptor()
with open(input_path, 'rb') as f_in, open(output_path, 'wb') as f_out:
# 先写入salt和IV(用于解密)
f_out.write(salt)
f_out.write(iv)
chunk = f_in.read(16)
while len(chunk) > 0:
if len(chunk) % 16 != 0:
# 填充到16字节对齐(PKCS7)
padding_len = 16 - (len(chunk) % 16)
chunk += bytes([padding_len]) * padding_len
encrypted_chunk = encryptor.update(chunk)
f_out.write(encrypted_chunk)
chunk = f_in.read(16)
# 完成加密
f_out.write(encryptor.finalize())
def decrypt_file(input_path: str, output_path: str, password: str):
with open(input_path, 'rb') as f_in, open(output_path, 'wb') as f_out:
# 读取salt和IV
salt = f_in.read(16)
iv = f_in.read(16)
# 用相同密码生成密钥
key = derive_key(password, salt)
cipher = Cipher(algorithms.AES(key), modes.CBC(iv))
decryptor = cipher.decryptor()
chunk = f_in.read(16)
buffer = b''
while len(chunk) > 0:
buffer += chunk
if len(buffer) % 16 == 0:
decrypted = decryptor.update(buffer)
f_out.write(decrypted)
buffer = b''
chunk = f_in.read(16)
# 处理最后一块(包含填充)
final_data = decryptor.finalize()
f_out.write(final_data)
# 可选:移除PKCS7填充(从末尾判断填充字节)
# 这里省略,实际应用中需处理encrypt_file("原文件.txt", "加密后.enc", "你的密码")decrypt_file("加密后.enc", "解密后.txt", "你的密码")基本上就这些。实现一个简易加密工具,重点是理解加密流程和避免常见陷阱。AES + PBKDF2 + salt + IV 的组合已经能满足基本安全需求,代码也不复杂,适合作为入门项目。
以上就是简易文件加密工具怎么做 基本加密算法实现方案的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号