Qwen3.5-9B实战教程:history.json加密存储+敏感信息脱敏处理方案

张开发
2026/5/22 19:28:55 15 分钟阅读
Qwen3.5-9B实战教程:history.json加密存储+敏感信息脱敏处理方案
Qwen3.5-9B实战教程history.json加密存储敏感信息脱敏处理方案1. 项目概述Qwen3.5-9B是一款拥有90亿参数的开源大语言模型具备强大的逻辑推理、代码生成和多轮对话能力。其多模态变体Qwen3.5-9B-VL支持图文输入并能处理长达128K tokens的上下文内容。在实际部署中我们发现对话历史记录文件history.json存在两个关键问题明文存储可能导致隐私泄露包含敏感信息时存在安全风险本文将详细介绍如何实现history.json文件的加密存储和敏感信息脱敏处理。2. 环境准备2.1 基础环境# 激活conda环境 conda activate torch28 # 安装额外依赖 pip install cryptography pycryptodome2.2 项目结构/root/qwen3.5-9b/ ├── app.py # 主程序 ├── start.sh # 启动脚本 ├── service.log # 运行日志 ├── history.json # 对话历史记录 └── security_utils.py # 新增的安全处理工具3. 加密存储实现方案3.1 AES加密实现创建security_utils.py文件from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad from Crypto.Random import get_random_bytes import base64 import json import os class HistoryEncryptor: def __init__(self, key_file.encryption_key): self.key_file key_file self.key self._get_or_create_key() def _get_or_create_key(self): if os.path.exists(self.key_file): with open(self.key_file, rb) as f: return f.read() else: key get_random_bytes(32) # AES-256 with open(self.key_file, wb) as f: f.write(key) os.chmod(self.key_file, 0o600) # 设置严格权限 return key def encrypt_data(self, data): cipher AES.new(self.key, AES.MODE_CBC) ct_bytes cipher.encrypt(pad(json.dumps(data).encode(), AES.block_size)) iv cipher.iv return base64.b64encode(iv ct_bytes).decode(utf-8) def decrypt_data(self, encrypted_data): try: data base64.b64decode(encrypted_data) iv data[:AES.block_size] ct data[AES.block_size:] cipher AES.new(self.key, AES.MODE_CBC, iv) pt unpad(cipher.decrypt(ct), AES.block_size) return json.loads(pt.decode(utf-8)) except Exception as e: print(f解密失败: {str(e)}) return None3.2 修改app.py集成加密功能from security_utils import HistoryEncryptor # 初始化加密器 encryptor HistoryEncryptor() def save_history(history): encrypted encryptor.encrypt_data(history) with open(history.json, w) as f: f.write(encrypted) def load_history(): try: with open(history.json, r) as f: encrypted f.read() return encryptor.decrypt_data(encrypted) or [] except FileNotFoundError: return []4. 敏感信息脱敏处理4.1 敏感信息检测规则import re class SensitiveInfoFilter: staticmethod def detect_sensitive_info(text): patterns { phone: r(?!\d)(1[3-9]\d{9})(?!\d), id_card: r([1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]), bank_card: r([1-9]\d{14,18}), email: r([a-zA-Z0-9._%-][a-zA-Z0-9.-]\.[a-zA-Z]{2,}) } detected {} for key, pattern in patterns.items(): matches re.findall(pattern, text) if matches: detected[key] [m[0] if isinstance(m, tuple) else m for m in matches] return detected staticmethod def mask_text(text, pattern_type, match): if pattern_type phone: return text.replace(match, match[:3] **** match[-4:]) elif pattern_type id_card: return text.replace(match, match[:6] ******** match[-4:]) elif pattern_type bank_card: return text.replace(match, match[:6] ****** match[-4:]) elif pattern_type email: parts match.split() return text.replace(match, parts[0][0] *** parts[1]) return text4.2 集成到对话处理流程def process_user_input(user_input): # 敏感信息检测与脱敏 filter SensitiveInfoFilter() sensitive_info filter.detect_sensitive_info(user_input) masked_input user_input for pattern_type, matches in sensitive_info.items(): for match in matches: masked_input filter.mask_text(masked_input, pattern_type, match) # 记录原始输入和脱敏后的输入 return { original: user_input, masked: masked_input, sensitive_info: sensitive_info } def chat_interface(user_input): processed process_user_input(user_input) # 使用processed[masked]作为模型输入 # ... 原有对话处理逻辑5. 完整实施方案5.1 修改后的history.json结构加密前的数据结构示例{ conversations: [ { timestamp: 2026-03-25T14:30:00, user_input: { original: 我的手机号是13812345678, masked: 我的手机号是138****5678, sensitive_info: { phone: [13812345678] } }, model_response: 已隐藏您的手机号信息 } ], metadata: { version: 1.0, encryption: AES-256-CBC, created_at: 2026-03-25 } }5.2 启动脚本修改更新start.sh确保加密密钥可用#!/bin/bash # 设置加密密钥权限 chmod 600 /root/qwen3.5-9b/.encryption_key 2/dev/null || true # 启动服务 python /root/qwen3.5-9b/app.py6. 安全增强措施6.1 定期轮换加密密钥def rotate_key(self): old_key self.key self.key get_random_bytes(32) # 重新加密所有历史数据 old_encryptor AES.new(old_key, AES.MODE_CBC) try: history self.load_history() self.save_history(history) with open(self.key_file, wb) as f: f.write(self.key) return True except Exception as e: print(f密钥轮换失败: {str(e)}) return False6.2 安全日志记录class SecurityLogger: LOG_FILE security_audit.log classmethod def log_access(cls, action, status, metadataNone): entry { timestamp: datetime.now().isoformat(), action: action, status: status, metadata: metadata or {} } with open(cls.LOG_FILE, a) as f: f.write(json.dumps(entry) \n)7. 总结本文介绍了Qwen3.5-9B模型中history.json文件的加密存储和敏感信息脱敏处理方案主要实现了AES-256加密存储确保对话历史文件即使被获取也无法直接读取敏感信息自动检测识别电话号码、身份证号等常见敏感信息实时脱敏处理在保存前自动替换敏感内容为掩码形式安全增强功能包括密钥轮换和安全审计日志实施本方案后可显著提升Qwen3.5-9B在生产环境中的安全性特别适用于需要处理用户隐私信息的应用场景。获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。

更多文章