如何创建可加密并保存用户输入个人数据的Command line程序
命令行个人数据加密存储程序开发落地方案
1. 核心需求拆解
- 支持接收用户命令行输入的个人数据,覆盖明文输入、本地文件批量导入两种常用场景
- 采用工业级加密算法处理明文,全程不会出现明文落盘的风险
- 加密后的数据支持本地持久化存储,同时配套解密查询、导出能力
- 密钥和加密数据隔离存储,避免单点泄露导致数据完全失控
2. 技术选型(跨平台低依赖方案)
- 开发语言选Python,跨Windows/Mac/Linux运行,无需编译,部署成本低
- 命令行参数解析用Python内置的
argparse库,无需额外安装第三方依赖 - 加密模块用
cryptography库的Fernet封装,底层是AES-128-CBC算法,自带MAC校验,能自动识别数据是否被篡改,符合通用安全标准 - 存储层用本地JSON文件,结构简单易维护,不需要额外部署数据库服务
3. 完整实现步骤
3.1 环境初始化
首先安装唯一的第三方依赖,执行命令:pip install cryptography
3.2 核心代码实现
把以下代码保存为secure_data_cli.py即可直接使用:
from cryptography.fernet import Fernet import argparse import json import os import sys # 生成唯一密钥,仅需首次运行时执行一次 def generate_key(key_save_path: str): key = Fernet.generate_key() with open(key_save_path, "wb") as f: f.write(key) # 加密明文数据 def encrypt_content(plain_content: str, key: bytes) -> bytes: fernet_handler = Fernet(key) return fernet_handler.encrypt(plain_content.encode("utf-8")) # 解密密文数据 def decrypt_content(encrypted_content: bytes, key: bytes) -> str: fernet_handler = Fernet(key) return fernet_handler.decrypt(encrypted_content).decode("utf-8") # 持久化存储加密后的数据,用标签做唯一标识方便查询 def save_to_storage(tag: str, encrypted_content: bytes, storage_path: str): storage_data = {} if os.path.exists(storage_path): with open(storage_path, "r", encoding="utf-8") as f: storage_data = json.load(f) storage_data[tag] = encrypted_content.decode("utf-8") with open(storage_path, "w", encoding="utf-8") as f: json.dump(storage_data, f, indent=2, ensure_ascii=False) if __name__ == "__main__": parser = argparse.ArgumentParser(description="个人数据加密存储CLI工具") parser.add_argument("--generate-key", type=str, help="首次使用生成密钥,指定密钥保存路径,例:--generate-key /home/xxx/my_key.key") parser.add_argument("--key", type=str, required=True, help="密钥文件的路径,所有加密解密操作都需要指定该参数") parser.add_argument("--tag", type=str, help="数据唯一标签,用于区分不同的个人数据") parser.add_argument("--save", type=str, help="要加密存储的明文,填-则从标准输入读取内容,避免命令历史泄露敏感数据") parser.add_argument("--load", type=str, help="要解密查询的数据标签") parser.add_argument("--storage-path", type=str, default="./encrypted_personal_data.json", help="加密数据存储路径,默认当前目录下的encrypted_personal_data.json") args = parser.parse_args() # 密钥生成逻辑 if args.generate_key: generate_key(args.generate_key) print(f"密钥已生成,保存路径:{args.generate_key},请妥善保管,丢失后所有加密数据无法恢复") exit(0) # 读取密钥 try: with open(args.key, "rb") as f: user_key = f.read() except FileNotFoundError: print("指定的密钥文件不存在,请检查路径是否正确") exit(1) # 加密存储逻辑 if args.save and args.tag: if args.save == "-": plain_data = sys.stdin.read().strip() else: plain_data = args.save encrypted_data = encrypt_content(plain_data, user_key) save_to_storage(args.tag, encrypted_data, args.storage_path) print(f"数据已加密存储,对应标签:{args.tag}") exit(0) # 解密查询逻辑 if args.load: if not os.path.exists(args.storage_path): print("加密数据存储文件不存在,暂无数据可查询") exit(1) with open(args.storage_path, "r", encoding="utf-8") as f: all_data = json.load(f) if args.load not in all_data: print(f"未找到对应标签{args.load}的数据") exit(1) encrypted_content = all_data[args.load].encode("utf-8") try: plain_content = decrypt_content(encrypted_content, user_key) except Exception as e: print("解密失败,可能是密钥错误或者数据被篡改") exit(1) print(f"标签{args.load}对应的明文数据:{plain_content}") exit(0) parser.print_help()
3.3 功能测试
- 首次使用生成密钥:
python secure_data_cli.py --generate-key ~/my_private_key.key --key ~/my_private_key.key - 加密存储敏感数据(从标准输入读取,避免命令历史泄露):
echo "1101011990XXXXXX" | python secure_data_cli.py --key ~/my_private_key.key --tag 身份证号 --save - - 查询解密指定标签的数据:
python secure_data_cli.py --key ~/my_private_key.key --load 身份证号
4. 安全加固建议
- 密钥和加密数据不要存在同一存储设备,建议密钥单独存在U盘或者离线密码管理器中
- Linux/Mac系统下给密钥文件加权限限制,执行
chmod 600 ~/my_private_key.key,仅当前用户可读写 - 可以额外加一层密码验证,调用加密解密功能前需要用户输入自定义密码解锁密钥,实现双重加密
- 定期备份加密数据文件,避免文件损坏导致数据丢失
内容的提问来源于stack exchange,提问作者MadMorphine
相关产品推荐
相关产品推荐

