在 Ubuntu 上给 Node.js 日志加密,常见做法有 应用层加密、传输加密、存储加密 几种思路。下面按“实际可落地”的方式给你讲清楚。
适合自定义日志模块。
const crypto = require('crypto');
const fs = require('fs');
const key = crypto.randomBytes(32); // 密钥要安全管理
const iv = crypto.randomBytes(16);
function encrypt(text) {
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
return encrypted;
}
const log = encrypt('user login success');
fs.appendFileSync('app.log.enc', log + '\n');
✅ 优点:日志本身就是密文
❌ 缺点:密钥管理复杂
适合已有日志系统。
const winston = require('winston');
const crypto = require('crypto');
const cipherKey = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
class EncryptFileTransport extends winston.Transport {
log(info, callback) {
const cipher = crypto.createCipheriv('aes-256-cbc', cipherKey, iv);
const enc = cipher.update(info.message, 'utf8', 'hex') + cipher.final('hex');
fs.appendFileSync('logs/enc.log', enc + '\n');
callback();
}
}
例如:
Node.js 示例(HTTPS):
axios.post('https://log-server.example.com/log', data, {
httpsAgent: new https.Agent({ rejectUnauthorized: true })
});
✅ 防止网络抓包
❌ 服务端仍是明文
适合“服务器被拿走”的场景。
Ubuntu 安装时勾选 LVM + Encryption
sudo apt install ecryptfs-utils
ecryptfs-setup-private
cryptsetup luksFormat /dev/sdb1
cryptsetup open /dev/sdb1 logenc
mkfs.ext4 /dev/mapper/logenc
✅ 透明、对 Node.js 无感
❌ 运行时不防 root 用户
chmod 600 /var/log/nodejs/*.log
chown node:node /var/log/nodejs
配合:
❌ 不要写死在代码里
✅ 使用:
EnvironmentFile| 场景 | 推荐方案 |
|---|---|
| 合规 / 敏感日志 | Node.js AES 加密 |
| 微服务集中日志 | TLS + 远端加密存储 |
| 服务器安全 | Ubuntu LUKS 加密 |
| 生产通用 | 加密 + 600 权限 |
如果你愿意,可以告诉我:
我可以直接给你一套完整配置。