// 输入净化函数示例 function sanitizeInput(input) { if (!input) return ''; // 移除危险标签和属性 return input.replace(/<script.*?>.*?<\/script>/gi, '') .replace(/<iframe.*?>.*?<\/iframe>/gi, '') .replace(/on\w+=".*?"/gi, '') .replace(/javascript:/gi, ''); } // 表单提交前验证 document.getElementById('userForm').addEventListener('submit', function(e) { const inputs = this.querySelectorAll('input, textarea'); inputs.forEach(input => { input.value = sanitizeInput(input.value); }); });

// 安全的Cookie设置示例 document.cookie = "sessionId=abc123; HttpOnly; Secure; SameSite=Strict; Max-Age=86400";
<!-- CSRF令牌示例 --> <form action="/user/profile" method="POST"> <input type="hidden" name="csrfToken" value="随机生成的令牌值"> <!-- 其他表单字段 --> <button type="submit">保存修改</button> </form>
// 敏感数据加密示例 const crypto = require('crypto'); // 加密配置 - 实际应用中应使用环境变量存储密钥 const ENCRYPTION_KEY = crypto.scryptSync(process.env.ENCRYPTION_SECRET, 'salt', 32); const IV_LENGTH = 16; // 加密函数 function encrypt(text) { const iv = crypto.randomBytes(IV_LENGTH); const cipher = crypto.createCipheriv('aes-256-cbc', ENCRYPTION_KEY, iv); let encrypted = cipher.update(text, 'utf8', 'hex'); encrypted += cipher.final('hex'); return `${iv.toString('hex')}:${encrypted}`; } // 解密函数 function decrypt(text) { const [ivHex, encryptedText] = text.split(':'); const iv = Buffer.from(ivHex, 'hex'); const decipher = crypto.createDecipheriv('aes-256-cbc', ENCRYPTION_KEY, iv); let decrypted = decipher.update(encryptedText, 'hex', 'utf8'); decrypted += decipher.final('utf8'); return decrypted; } // 使用示例 const creditCardNumber = '4111111111111111'; const encryptedCC = encrypt(creditCardNumber); console.log('加密后:', encryptedCC); const decryptedCC = decrypt(encryptedCC); console.log('解密后:', decryptedCC);
// 错误示例 - 存在SQL注入风险 const userId = req.query.id; // 直接拼接用户输入到SQL中是危险的! db.query(`SELECT * FROM users WHERE id = ${userId}`, (err, results) => { // 处理结果 }); // 安全示例 - 使用参数化查询 const userId = req.query.id; // 使用?作为占位符,避免SQL注入 db.query('SELECT * FROM users WHERE id = ?', [userId], (err, results) => { // 处理结果 }); // ORM示例 - 更安全的方式 const userId = req.query.id; const user = await User.findByPk(userId); // Sequelize示例
# 服务器安全配置示例(Linux) # 更新系统 sudo apt update && sudo apt upgrade -y # 安装防火墙并配置 sudo apt install ufw -y sudo ufw default deny incoming sudo ufw default allow outgoing sudo ufw allow ssh sudo ufw allow https sudo ufw enable sudo ufw status # 禁用密码登录,启用SSH密钥认证 sudo sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config sudo systemctl restart sshd # 安装并配置fail2ban防止暴力攻击 sudo apt install fail2ban -y sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local sudo systemctl enable fail2ban sudo systemctl start fail2ban