feat(react-web-next): 新增.editorconfig和.prettierrc配置文件,添加public/.gitkeep占位文件
This commit is contained in:
@@ -0,0 +1,202 @@
|
||||
# 前端RSA加密使用指南
|
||||
|
||||
## 概述
|
||||
|
||||
本项目提供了与后端RSAUtil对应的前端RSA加密解决方案,确保敏感数据在传输过程中的安全性。
|
||||
|
||||
## 核心文件
|
||||
|
||||
- `rsaUtil.ts` - RSA加密核心工具类
|
||||
- `securityUtil.ts` - 安全辅助工具类
|
||||
- `useSecurity.ts` - React Hook,提供安全操作
|
||||
- `SecureLoginForm` - 安全登录表单组件
|
||||
|
||||
## 基本使用
|
||||
|
||||
### 1. 密码加密
|
||||
|
||||
```typescript
|
||||
import RSAUtil from '@/utils/rsaUtil';
|
||||
|
||||
// 加密密码
|
||||
const encryptedPassword = RSAUtil.encryptPassword('user123456');
|
||||
|
||||
// 或使用便捷导入
|
||||
import { encryptPassword } from '@/utils/rsaUtil';
|
||||
const encrypted = encryptPassword('user123456');
|
||||
```
|
||||
|
||||
### 2. 登录表单处理
|
||||
|
||||
```typescript
|
||||
import { useSecurity } from '@/hooks/useSecurity';
|
||||
|
||||
const LoginPage = () => {
|
||||
const { secureLogin } = useSecurity();
|
||||
|
||||
const handleLogin = async (values) => {
|
||||
const secureData = await secureLogin(values);
|
||||
if (secureData) {
|
||||
// 发送到后端
|
||||
api.login(secureData);
|
||||
}
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
### 3. 批量敏感字段加密
|
||||
|
||||
```typescript
|
||||
import SecurityUtil from '@/utils/securityUtil';
|
||||
|
||||
const userForm = {
|
||||
username: 'admin',
|
||||
password: '123456',
|
||||
email: 'admin@example.com'
|
||||
};
|
||||
|
||||
// 只加密密码字段
|
||||
const secureForm = SecurityUtil.processFormData(userForm, ['password']);
|
||||
```
|
||||
|
||||
### 4. 使用安全登录组件
|
||||
|
||||
```typescript
|
||||
import SecureLoginForm from '@/components/SecureLoginForm';
|
||||
|
||||
const LoginPage = () => {
|
||||
const handleLogin = async (loginData) => {
|
||||
// loginData.password 已经被自动加密
|
||||
const response = await api.login(loginData);
|
||||
// 处理登录响应
|
||||
};
|
||||
|
||||
return (
|
||||
<SecureLoginForm
|
||||
onLogin={handleLogin}
|
||||
showPasswordStrength={true}
|
||||
/>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
## 安全最佳实践
|
||||
|
||||
### 1. 加密时机
|
||||
- ✅ 在发送请求前立即加密
|
||||
- ✅ 在表单提交时加密
|
||||
- ❌ 不要在组件状态中存储加密数据
|
||||
- ❌ 不要过早加密(影响用户体验)
|
||||
|
||||
### 2. 错误处理
|
||||
```typescript
|
||||
const encryptedData = RSAUtil.encrypt(sensitiveData);
|
||||
if (!encryptedData) {
|
||||
// 处理加密失败
|
||||
message.error('数据加密失败,请重试');
|
||||
return;
|
||||
}
|
||||
```
|
||||
|
||||
### 3. 加密前验证
|
||||
```typescript
|
||||
// 密码强度验证
|
||||
const strength = SecurityUtil.validatePasswordStrength(password);
|
||||
if (strength.level === 'weak') {
|
||||
// 提示用户增强密码
|
||||
}
|
||||
|
||||
// 输入安全过滤
|
||||
const safeInput = SecurityUtil.sanitizeInput(userInput);
|
||||
```
|
||||
|
||||
### 4. 敏感数据脱敏
|
||||
```typescript
|
||||
// 显示时脱敏
|
||||
const maskedPhone = SecurityUtil.maskSensitiveData('13812345678', 'phone');
|
||||
// 结果: 138****5678
|
||||
```
|
||||
|
||||
## 与后端对接
|
||||
|
||||
### 后端解密示例
|
||||
你的后端使用 `RSAUtil.decryptOne()` 方法解密:
|
||||
|
||||
```java
|
||||
// Java后端
|
||||
String rawPassword = RSAUtil.decryptOne(req.getPassword());
|
||||
```
|
||||
|
||||
### 前后端数据流程
|
||||
1. 前端: 用户输入密码 `"123456"`
|
||||
2. 前端: RSA加密 → `"LBS9qzlDcBQ..."`(Base64 + URL编码)
|
||||
3. 后端: 接收加密数据
|
||||
4. 后端: `RSAUtil.decryptOne()` 解密 → `"123456"`
|
||||
|
||||
## 安全注意事项
|
||||
|
||||
### 1. 公钥管理
|
||||
- 公钥已硬编码在代码中(与后端保持一致)
|
||||
- 生产环境建议通过API动态获取公钥
|
||||
- 定期轮换密钥对
|
||||
|
||||
### 2. HTTPS传输
|
||||
```typescript
|
||||
// 确保API请求使用HTTPS
|
||||
const API_BASE_URL = process.env.NODE_ENV === 'production'
|
||||
? 'https://your-domain.com/api'
|
||||
: 'http://localhost:9900';
|
||||
```
|
||||
|
||||
### 3. 内存安全
|
||||
```typescript
|
||||
// 避免在控制台输出敏感信息
|
||||
if (process.env.NODE_ENV !== 'development') {
|
||||
console.log = () => {};
|
||||
}
|
||||
```
|
||||
|
||||
### 4. 输入验证
|
||||
```typescript
|
||||
// 在加密前验证输入
|
||||
if (!password || password.trim() === '') {
|
||||
throw new Error('密码不能为空');
|
||||
}
|
||||
|
||||
if (password.length < 6) {
|
||||
throw new Error('密码长度不能少于6位');
|
||||
}
|
||||
```
|
||||
|
||||
## 常见问题
|
||||
|
||||
### Q: 加密失败怎么办?
|
||||
A: 检查输入数据是否为空,确认jsencrypt库已正确安装
|
||||
|
||||
### Q: 前后端加密解密不匹配?
|
||||
A: 确认公钥私钥对是否一致,检查Base64编码格式
|
||||
|
||||
### Q: 性能优化建议?
|
||||
A:
|
||||
- RSA加密较慢,只加密敏感字段
|
||||
- 考虑使用Web Worker处理大量数据加密
|
||||
- 合理使用缓存
|
||||
|
||||
## 测试
|
||||
|
||||
```typescript
|
||||
// 简单测试
|
||||
const testData = 'test123';
|
||||
const encrypted = RSAUtil.encrypt(testData);
|
||||
console.log('加密结果:', encrypted);
|
||||
console.log('是否已加密:', RSAUtil.isEncrypted(encrypted));
|
||||
```
|
||||
|
||||
## 升级指南
|
||||
|
||||
如需更新加密算法或密钥:
|
||||
|
||||
1. 与后端协调更新时间
|
||||
2. 更新 `rsaUtil.ts` 中的公钥
|
||||
3. 测试前后端对接
|
||||
4. 发布更新
|
||||
@@ -0,0 +1,69 @@
|
||||
// 通用下载工具(中文注释)
|
||||
// 使用方式:
|
||||
// const res = await request(url, { responseType: 'blob', getResponse: true });
|
||||
// download(res, '默认文件名.xlsx');
|
||||
|
||||
// 解析 Content-Disposition,优先 filename*,其次 filename
|
||||
function getFilenameFromHeaders(headers?: Headers, fallback = 'download') {
|
||||
try {
|
||||
const cd = headers?.get('content-disposition') || headers?.get('Content-Disposition') || '';
|
||||
// filename*="UTF-8''xxx"
|
||||
const star = /filename\*=(?:UTF-8'')?"?([^";]+)"?/i.exec(cd);
|
||||
if (star && star[1]) {
|
||||
try {
|
||||
return decodeURIComponent(star[1]);
|
||||
} catch {
|
||||
return star[1];
|
||||
}
|
||||
}
|
||||
// filename="xxx"
|
||||
const normal = /filename="?([^";]+)"?/i.exec(cd);
|
||||
if (normal && normal[1]) return normal[1];
|
||||
} catch {}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
export function download(
|
||||
result: { data?: any; response?: Response } | Blob | Response,
|
||||
defaultName = 'download'
|
||||
) {
|
||||
let blob: Blob | null = null;
|
||||
let headers: Headers | undefined = undefined;
|
||||
|
||||
if (result instanceof Blob) {
|
||||
blob = result;
|
||||
} else if (result instanceof Response) {
|
||||
// 假设调用侧已传入 getResponse:true + responseType:'blob' 时不会走到这里
|
||||
// 如果走到这里,说明未读出 blob,此处放弃自动读取,交由调用侧修正
|
||||
// 为避免未读流引发问题,直接返回
|
||||
return;
|
||||
} else if (result && typeof result === 'object') {
|
||||
blob = (result as any).data as Blob;
|
||||
headers = (result as any).response?.headers as Headers;
|
||||
}
|
||||
|
||||
if (!blob) return;
|
||||
|
||||
const filename = getFilenameFromHeaders(headers, defaultName);
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.style.display = 'none';
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
// 通过 URL 直接触发浏览器下载(不读取内容,兼容无 CORS 的场景)
|
||||
export function downloadByUrl(url: string, filename?: string) {
|
||||
if (!url) return;
|
||||
const a = document.createElement('a');
|
||||
a.style.display = 'none';
|
||||
a.href = url;
|
||||
if (filename) a.download = filename;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// 前端 Excel 导出工具(中文注释)
|
||||
// 用于将页面内存数据导出为 xlsx 文件(与老项目保持一致 API)
|
||||
import { saveAs } from 'file-saver';
|
||||
import * as XLSX from 'xlsx';
|
||||
|
||||
export interface ExportHeader {
|
||||
title: string; // 表头名
|
||||
dataIndex: string; // 对应数据字段
|
||||
}
|
||||
|
||||
export interface ExportExcelParams {
|
||||
data: any[]; // 原始数据数组
|
||||
header: ExportHeader[]; // 表头定义
|
||||
fileName: string; // 文件名(不含扩展名)
|
||||
}
|
||||
|
||||
export const exportExcel = ({ data, header, fileName }: ExportExcelParams) => {
|
||||
try {
|
||||
const excelData = (data || []).map((item) => {
|
||||
const row: Record<string, any> = {};
|
||||
header.forEach((h) => {
|
||||
row[h.title] = (item as any)[h.dataIndex];
|
||||
});
|
||||
return row;
|
||||
});
|
||||
|
||||
const wb = XLSX.utils.book_new();
|
||||
const ws = XLSX.utils.json_to_sheet(excelData, { header: header.map((h) => h.title) });
|
||||
XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
|
||||
|
||||
const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
|
||||
const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
|
||||
saveAs(blob, `${fileName}.xlsx`);
|
||||
} catch (e) {
|
||||
// 仅记录错误,避免阻断页面
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('导出 Excel 失败: ', e);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { extend } from 'umi-request';
|
||||
|
||||
const client = extend({
|
||||
timeout: 20000,
|
||||
});
|
||||
|
||||
client.interceptors.response.use(async (response: any) => {
|
||||
const data = await response.clone().json().catch(() => undefined);
|
||||
if (data && typeof data.resp_code !== 'undefined') {
|
||||
// 兼容后端 Result 结构
|
||||
return {
|
||||
success: data.resp_code === 0,
|
||||
code: data.resp_code,
|
||||
msg: data.resp_msg,
|
||||
data: data.data,
|
||||
} as any;
|
||||
}
|
||||
return response;
|
||||
});
|
||||
|
||||
export default client;
|
||||
@@ -0,0 +1,206 @@
|
||||
import * as JSEncryptLib from 'jsencrypt';
|
||||
|
||||
// 确定正确的JSEncrypt构造函数
|
||||
const JSEncrypt = JSEncryptLib.JSEncrypt || JSEncryptLib.default || JSEncryptLib;
|
||||
|
||||
/**
|
||||
* RSA加密工具类 - 与后端RSAUtil对应
|
||||
* 用于前端敏感数据加密,后端解密
|
||||
*/
|
||||
export class RSAUtil {
|
||||
// 与后端genKeyPair()方法中固定的公钥保持一致
|
||||
private static readonly PUBLIC_KEY_RAW =
|
||||
'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCGu7lYGfEtMICO8kREJrObu0Hy' +
|
||||
'pF7R9iEIefyxApmB6wJ/y3Rg/eBO6kLDCo18hYZ3ZNxKp5CMymZvXDh5j+sd7IHm' +
|
||||
'tUh6sEZzpXExQJIzT8gA1SULd+iXe4V9zt2AcbROIi94vA6lOfmtON28Ex+uAlLK' +
|
||||
'N/iJDXFFXdEOmfdqhwIDAQAB';
|
||||
|
||||
// 格式化为PEM格式的公钥
|
||||
private static readonly PUBLIC_KEY =
|
||||
'-----BEGIN PUBLIC KEY-----\n' +
|
||||
RSAUtil.PUBLIC_KEY_RAW +
|
||||
'\n-----END PUBLIC KEY-----';
|
||||
|
||||
// 由于 jsencrypt 未提供完善的类型定义,这里使用 any 规避类型问题
|
||||
private static jsEncrypt: any = null;
|
||||
|
||||
/**
|
||||
* 获取或创建JSEncrypt实例
|
||||
*/
|
||||
private static getJSEncryptInstance(): any {
|
||||
try {
|
||||
// 每次都创建新实例,避免缓存问题
|
||||
const jsEncrypt: any = new JSEncrypt();
|
||||
|
||||
console.log('创建新的JSEncrypt实例');
|
||||
|
||||
// 首先尝试PEM格式
|
||||
jsEncrypt.setPublicKey(this.PUBLIC_KEY);
|
||||
|
||||
if (!jsEncrypt.getPublicKey()) {
|
||||
console.log('PEM格式失败,尝试原始格式');
|
||||
jsEncrypt.setPublicKey(this.PUBLIC_KEY_RAW);
|
||||
}
|
||||
|
||||
// 最终验证
|
||||
if (!jsEncrypt.getPublicKey()) {
|
||||
throw new Error('公钥设置失败');
|
||||
}
|
||||
|
||||
// 验证encrypt方法是否存在
|
||||
if (typeof jsEncrypt.encrypt !== 'function') {
|
||||
throw new Error('JSEncrypt实例的encrypt方法不存在');
|
||||
}
|
||||
|
||||
console.log('JSEncrypt实例创建成功,encrypt方法类型:', typeof jsEncrypt.encrypt);
|
||||
return jsEncrypt;
|
||||
} catch (error) {
|
||||
console.error('JSEncrypt实例创建失败:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用公钥加密数据
|
||||
* @param data 要加密的明文数据
|
||||
* @returns 加密后的Base64字符串,已进行URL编码处理(将"/"替换为"%2F")
|
||||
*/
|
||||
public static encrypt(data: string): string | null {
|
||||
try {
|
||||
console.log('开始创建JSEncrypt实例...');
|
||||
const jsEncryptInstance = this.getJSEncryptInstance();
|
||||
|
||||
console.log('开始执行加密操作...');
|
||||
const encrypted = jsEncryptInstance.encrypt(data);
|
||||
|
||||
if (!encrypted) {
|
||||
console.error('RSA加密失败,encrypt方法返回null或false');
|
||||
return null;
|
||||
}
|
||||
|
||||
console.log('加密成功,原始结果长度:', encrypted.length);
|
||||
// 与后端encryptOne方法保持一致,将"/"替换为"%2F"
|
||||
const result = encrypted.replace(/\//g, '%2F');
|
||||
console.log('URL编码后长度:', result.length);
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.error('RSA加密异常:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 直接加密方法 - 绕过类方法调用
|
||||
*/
|
||||
public static directEncrypt(data: string): string | null {
|
||||
try {
|
||||
console.log('直接加密方法,数据长度:', data.length);
|
||||
console.log('JSEncrypt类型:', typeof JSEncrypt);
|
||||
|
||||
if (typeof JSEncrypt !== 'function') {
|
||||
console.error('JSEncrypt不是函数');
|
||||
return null;
|
||||
}
|
||||
|
||||
const crypt = new JSEncrypt();
|
||||
console.log('JSEncrypt实例创建成功,实例类型:', typeof crypt);
|
||||
console.log('encrypt方法类型:', typeof crypt.encrypt);
|
||||
|
||||
// 设置公钥
|
||||
crypt.setPublicKey(this.PUBLIC_KEY_RAW);
|
||||
console.log('公钥设置完成');
|
||||
|
||||
// 执行加密
|
||||
const encrypted = crypt.encrypt(data);
|
||||
console.log('加密结果:', encrypted ? '成功' : '失败');
|
||||
|
||||
if (encrypted) {
|
||||
return encrypted.replace(/\//g, '%2F');
|
||||
}
|
||||
return null;
|
||||
} catch (error) {
|
||||
console.error('直接加密异常:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 加密密码 - 专门用于密码字段的加密
|
||||
* @param password 原始密码
|
||||
* @returns 加密后的密码字符串
|
||||
*/
|
||||
public static encryptPassword(password: string): string | null {
|
||||
if (!password || password.trim() === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
if (typeof JSEncrypt !== 'function') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const crypt = new JSEncrypt();
|
||||
crypt.setPublicKey(RSAUtil.PUBLIC_KEY_RAW);
|
||||
const encrypted = crypt.encrypt(password);
|
||||
|
||||
if (encrypted) {
|
||||
return encrypted.replace(/\//g, '%2F');
|
||||
}
|
||||
return null;
|
||||
} catch (error) {
|
||||
console.error('RSA加密失败:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量加密对象中的敏感字段
|
||||
* @param data 包含敏感字段的对象
|
||||
* @param sensitiveFields 需要加密的字段名数组
|
||||
* @returns 处理后的对象(敏感字段已加密)
|
||||
*/
|
||||
public static encryptSensitiveFields<T extends Record<string, any>>(
|
||||
data: T,
|
||||
sensitiveFields: (keyof T)[]
|
||||
): T {
|
||||
const result = { ...data };
|
||||
|
||||
sensitiveFields.forEach(field => {
|
||||
if (result[field] && typeof result[field] === 'string') {
|
||||
const encrypted = this.encrypt(result[field] as string);
|
||||
if (encrypted) {
|
||||
result[field] = encrypted as T[keyof T];
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否已加密(简单判断是否包含Base64字符和%2F)
|
||||
* @param data 要检查的数据
|
||||
* @returns 是否已加密
|
||||
*/
|
||||
public static isEncrypted(data: string): boolean {
|
||||
if (!data) return false;
|
||||
// 简单判断:包含%2F且长度较长且符合Base64模式
|
||||
return data.includes('%2F') && data.length > 100 && /^[A-Za-z0-9+%=\/]+$/.test(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取公钥(仅用于调试,生产环境不建议暴露)
|
||||
* @returns 公钥字符串
|
||||
*/
|
||||
public static getPublicKey(): string {
|
||||
return this.PUBLIC_KEY;
|
||||
}
|
||||
}
|
||||
|
||||
// 默认导出
|
||||
export default RSAUtil;
|
||||
|
||||
// 便捷方法导出
|
||||
export const encryptPassword = RSAUtil.encryptPassword;
|
||||
export const encryptData = RSAUtil.encrypt;
|
||||
export const encryptSensitiveFields = RSAUtil.encryptSensitiveFields;
|
||||
@@ -0,0 +1,172 @@
|
||||
import RSAUtil from './rsaUtil';
|
||||
|
||||
/**
|
||||
* 安全工具类 - 提供常用的安全操作
|
||||
*/
|
||||
export class SecurityUtil {
|
||||
|
||||
/**
|
||||
* 安全登录请求处理
|
||||
* @param loginData 登录数据
|
||||
* @returns 处理后的登录数据(密码已加密)
|
||||
*/
|
||||
public static processLoginData(loginData: {
|
||||
username: string;
|
||||
password: string;
|
||||
[key: string]: any;
|
||||
}) {
|
||||
const processedData = { ...loginData };
|
||||
|
||||
// 加密密码
|
||||
if (processedData.password) {
|
||||
const encryptedPassword = RSAUtil.encryptPassword(processedData.password);
|
||||
if (encryptedPassword) {
|
||||
processedData.password = encryptedPassword;
|
||||
} else {
|
||||
throw new Error('密码加密失败,请重试');
|
||||
}
|
||||
}
|
||||
|
||||
return processedData;
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全表单数据处理
|
||||
* @param formData 表单数据
|
||||
* @param sensitiveFields 敏感字段列表
|
||||
* @returns 处理后的表单数据
|
||||
*/
|
||||
public static processFormData<T extends Record<string, any>>(
|
||||
formData: T,
|
||||
sensitiveFields: (keyof T)[] = ['password', 'confirmPassword', 'oldPassword', 'newPassword']
|
||||
): T {
|
||||
return RSAUtil.encryptSensitiveFields(formData, sensitiveFields);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证密码强度
|
||||
* @param password 密码
|
||||
* @returns 密码强度等级和提示信息
|
||||
*/
|
||||
public static validatePasswordStrength(password: string): {
|
||||
level: 'weak' | 'medium' | 'strong';
|
||||
score: number;
|
||||
suggestions: string[];
|
||||
} {
|
||||
const suggestions: string[] = [];
|
||||
let score = 0;
|
||||
|
||||
// 长度检查
|
||||
if (password.length >= 8) {
|
||||
score += 25;
|
||||
} else {
|
||||
suggestions.push('密码长度至少8位');
|
||||
}
|
||||
|
||||
// 包含小写字母
|
||||
if (/[a-z]/.test(password)) {
|
||||
score += 15;
|
||||
} else {
|
||||
suggestions.push('包含小写字母');
|
||||
}
|
||||
|
||||
// 包含大写字母
|
||||
if (/[A-Z]/.test(password)) {
|
||||
score += 15;
|
||||
} else {
|
||||
suggestions.push('包含大写字母');
|
||||
}
|
||||
|
||||
// 包含数字
|
||||
if (/\d/.test(password)) {
|
||||
score += 15;
|
||||
} else {
|
||||
suggestions.push('包含数字');
|
||||
}
|
||||
|
||||
// 包含特殊字符
|
||||
if (/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(password)) {
|
||||
score += 20;
|
||||
} else {
|
||||
suggestions.push('包含特殊字符(!@#$%^&*等)');
|
||||
}
|
||||
|
||||
// 长度奖励
|
||||
if (password.length >= 12) {
|
||||
score += 10;
|
||||
}
|
||||
|
||||
let level: 'weak' | 'medium' | 'strong';
|
||||
if (score >= 70) {
|
||||
level = 'strong';
|
||||
} else if (score >= 50) {
|
||||
level = 'medium';
|
||||
} else {
|
||||
level = 'weak';
|
||||
}
|
||||
|
||||
return { level, score, suggestions };
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全的输入过滤(基础XSS防护)
|
||||
* @param input 用户输入
|
||||
* @returns 过滤后的输入
|
||||
*/
|
||||
public static sanitizeInput(input: string): string {
|
||||
if (!input) return '';
|
||||
|
||||
return input
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''')
|
||||
.replace(/\//g, '/');
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成随机盐值(用于额外安全性)
|
||||
* @param length 盐值长度
|
||||
* @returns 随机盐值
|
||||
*/
|
||||
public static generateSalt(length: number = 16): string {
|
||||
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
||||
let salt = '';
|
||||
for (let i = 0; i < length; i++) {
|
||||
salt += chars.charAt(Math.floor(Math.random() * chars.length));
|
||||
}
|
||||
return salt;
|
||||
}
|
||||
|
||||
/**
|
||||
* 敏感信息脱敏显示
|
||||
* @param data 敏感数据
|
||||
* @param type 数据类型
|
||||
* @returns 脱敏后的数据
|
||||
*/
|
||||
public static maskSensitiveData(data: string, type: 'phone' | 'email' | 'idcard' | 'bankcard'): string {
|
||||
if (!data) return '';
|
||||
|
||||
switch (type) {
|
||||
case 'phone':
|
||||
return data.length >= 11 ? data.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') : data;
|
||||
case 'email':
|
||||
const [username, domain] = data.split('@');
|
||||
if (username && domain) {
|
||||
const maskedUsername = username.length > 2
|
||||
? username[0] + '*'.repeat(username.length - 2) + username[username.length - 1]
|
||||
: username;
|
||||
return `${maskedUsername}@${domain}`;
|
||||
}
|
||||
return data;
|
||||
case 'idcard':
|
||||
return data.length >= 15 ? data.replace(/(\d{6})\d{8}(\d{4})/, '$1********$2') : data;
|
||||
case 'bankcard':
|
||||
return data.length >= 16 ? data.replace(/(\d{4})\d{8}(\d{4})/, '$1********$2') : data;
|
||||
default:
|
||||
return data;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default SecurityUtil;
|
||||
@@ -0,0 +1,24 @@
|
||||
export interface TreeNode<T=any> {
|
||||
key: string | number;
|
||||
title: string;
|
||||
children?: TreeNode<T>[];
|
||||
raw?: T;
|
||||
}
|
||||
|
||||
export function buildTree<T extends { id: any; pId?: any; name?: string }>(list: T[]): TreeNode<T>[] {
|
||||
const map = new Map<any, TreeNode<T>>();
|
||||
const roots: TreeNode<T>[] = [];
|
||||
list.forEach(item => {
|
||||
map.set(item.id, { key: item.id, title: (item as any).title || item.name || String(item.id), raw: item, children: [] });
|
||||
});
|
||||
list.forEach(item => {
|
||||
const node = map.get(item.id)!;
|
||||
if (item.pId && map.has(item.pId)) {
|
||||
map.get(item.pId)!.children!.push(node);
|
||||
} else {
|
||||
roots.push(node);
|
||||
}
|
||||
});
|
||||
return roots;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user