你说的“Node 扩展”可能有几种不同含义,我先分几种常见场景来解释 Node.js 中如何做加密,你可以看哪一种符合你的需求。
Node.js 自带 crypto 模块,不需要额外安装。
适合:加密配置、敏感数据
const crypto = require('crypto');
const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32); // 密钥
const iv = crypto.randomBytes(16); // 初始化向量
function encrypt(text) {
const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
return encrypted;
}
function decrypt(encrypted) {
const decipher = crypto.createDecipheriv(algorithm, key, iv);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
const data = 'secret';
const enc = encrypt(data);
console.log(enc);
console.log(decrypt(enc));
适合:密码存储
const crypto = require('crypto');
const hash = crypto.createHash('sha256')
.update('password')
.digest('hex');
console.log(hash);
✅ 推荐密码用 bcrypt / scrypt / argon2
npm install bcrypt
const bcrypt = require('bcrypt');
const saltRounds = 10;
bcrypt.hash('password', saltRounds).then(hash => {
console.log(hash);
});
如果你是问 Node 扩展(.node / N-API / C++ 插件)如何加密代码或数据:
Node 内部用的就是 OpenSSL,你也可以直接调用。
#include <openssl/aes.h>
#include <openssl/rand.h>
编译时链接 OpenSSL。
常见做法:
.node(比 JS 难反编译)如果你是想 防止别人看 Node.js 源码:
npm install javascript-obfuscator
pkgnexeelectron(桌面)你可以告诉我:
1️⃣ Node.js 数据加密
2️⃣ Node 原生扩展(C++)
3️⃣ 防止 JS 被反编译
4️⃣ 某个具体库(如 Electron / N-API)
我可以直接给你完整示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。