
从零实现敏感数据的安全存储与传输
在网络安全日益重要的今天,如何保护敏感数据成为每个开发者必须面对的课题。今天,我们将通过Python的cryptography库中的Fernet模块,带你实现一个简单而强大的文件加密解密方案。
Fernet是一种对称加密算法,它保证:
它使用AES-128加密和PKCS7填充,配合HMAC-SHA256验证,是目前最可靠的对称加密方案之一。
from cryptography.fernet import Fernet# 1. 生成密钥key = Fernet.generate_key()cipher = Fernet(key)# 2. 原始敏感数据(必须为bytes类型)message = b"Sensitive Cybersecurity Data"# 3. 加密encrypted = cipher.encrypt(message)# 4. 解密decrypted = cipher.decrypt(encrypted)# 5. 输出结果print("加密后:", encrypted)print("解密后:", decrypted)加密后: b'gAAAAABpkuauj6jHeQ5a2IOUt88kKxZaaEo_TM24g='解密后: b'Sensitive Cybersecurity Data'key = Fernet.generate_key()cipher = Fernet(key)encrypted = cipher.encrypt(message)decrypted = cipher.decrypt(encrypted)上面的示例加密的是字符串,实际应用中我们往往需要加密文件。下面是两个实用函数:
defencrypt_file(file_path, key): cipher = Fernet(key)with open(file_path, 'rb') as file: file_data = file.read() encrypted_data = cipher.encrypt(file_data)with open(file_path + '.encrypted', 'wb') as file: file.write(encrypted_data) print(f"文件已加密保存为: {file_path}.encrypted")defdecrypt_file(encrypted_path, key, output_path=None): cipher = Fernet(key)with open(encrypted_path, 'rb') as file: encrypted_data = file.read() decrypted_data = cipher.decrypt(encrypted_data)if output_path isNone: output_path = encrypted_path.replace('.encrypted', '')with open(output_path, 'wb') as file: file.write(decrypted_data) print(f"文件已解密为: {output_path}")# 生成密钥(实际应用中应安全存储)key = Fernet.generate_key()# 加密配置文件encrypt_file('config.ini', key)# 解密文件decrypt_file('config.ini.encrypted', key, 'config_restored.ini')import osfrom cryptography.fernet import Fernetdefbatch_encrypt(folder_path, key, extensions=None):""" 批量加密指定文件夹中的文件 :param folder_path: 文件夹路径 :param key: Fernet密钥 :param extensions: 要加密的文件扩展名列表,如['.txt', '.conf'] """ cipher = Fernet(key)for root, dirs, files in os.walk(folder_path):for file in files:if extensions andnot any(file.endswith(ext) for ext in extensions):continue file_path = os.path.join(root, file)with open(file_path, 'rb') as f: data = f.read() encrypted = cipher.encrypt(data)with open(file_path + '.enc', 'wb') as f: f.write(encrypted) print(f"已加密: {file_path}")# 使用示例key = Fernet.generate_key()batch_encrypt('/path/to/sensitive/docs', key, ['.txt', '.pdf', '.docx'])❌ 错误做法:
key = b'my_secret_key_12345'# 绝不!✅ 正确做法:
# 从环境变量读取import oskey = os.environ.get('ENCRYPTION_KEY').encode()# 从密钥文件读取with open('secret.key', 'rb') as f: key = f.read()定期更换密钥,并用新密钥重新加密敏感数据。
.encode()转换defencrypt_large_file(file_path, key, chunk_size=64*1024): cipher = Fernet(key)with open(file_path, 'rb') as f_in:with open(file_path + '.enc', 'wb') as f_out:whileTrue: chunk = f_in.read(chunk_size)ifnot chunk:break encrypted_chunk = cipher.encrypt(chunk) f_out.write(encrypted_chunk)Fernet提供了一种简单但强大的加密方案,只需几行代码就能为你的敏感数据加上坚固的防护:
Fernet.generate_key()Fernet(key)cipher.encrypt(data)cipher.decrypt(encrypted)无论你是保护配置文件、用户隐私数据,还是实现安全的文件传输,Fernet都是一个值得信赖的选择。
记住:在网络安全的世界里,加密不是可选项,而是必选项。
