浅谈Nodejs中的Crypto模块
浅谈Nodejs中的Crypto模块
好文绑定。目前的实践主要是网站密码的加密存储使用,应该可以借鉴上。
浅谈Node.js中的Crypto模块
Node.js 提供了一个强大的 crypto
模块,用于实现各种加密操作,包括哈希(hash)、HMAC、加密解密以及签名验证等。通过这些功能,我们可以更安全地处理数据,尤其是在处理用户密码时。
1. 哈希(Hash)
哈希是一种将任意长度的数据转换为固定长度输出的技术。哈希算法通常用于生成文件或数据的指纹,以确保其完整性。在 Node.js 中,我们可以使用 crypto
模块来创建哈希值。
const crypto = require('crypto');
// 创建一个 SHA256 哈希对象
const hash = crypto.createHash('sha256');
// 更新哈希对象的内容
hash.update('Hello, world!');
// 获取哈希值
const result = hash.digest('hex'); // 转换为十六进制字符串
console.log(result); // 输出哈希值
2. HMAC (Hash-based Message Authentication Code)
HMAC 是一种使用哈希函数和密钥生成的消息认证码。它可以用来验证数据的完整性和来源。在 Node.js 中,我们可以通过 crypto
模块来创建 HMAC。
const crypto = require('crypto');
const key = 'mySecretKey';
// 创建一个 HMAC 对象
const hmac = crypto.createHmac('sha256', key);
// 更新 HMAC 对象的内容
hmac.update('Hello, world!');
// 获取 HMAC 值
const result = hmac.digest('hex'); // 转换为十六进制字符串
console.log(result); // 输出 HMAC 值
3. 加密和解密
crypto
模块还支持对称加密算法,如 AES(高级加密标准)。我们可以使用这些算法对敏感数据进行加密和解密。
const crypto = require('crypto');
const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
// 加密函数
function encrypt(text) {
let cipher = crypto.createCipheriv(algorithm, Buffer.from(key), iv);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return { iv: iv.toString('hex'), encryptedData: encrypted.toString('hex') };
}
// 解密函数
function decrypt(encrypted) {
let iv = Buffer.from(encrypted.iv, 'hex');
let encryptedText = Buffer.from(encrypted.encryptedData, 'hex');
let decipher = crypto.createDecipheriv(algorithm, Buffer.from(key), iv);
let decrypted = decipher.update(encryptedText);
decrypted = Buffer.concat([decrypted, decipher.final()]);
return decrypted.toString();
}
let originalText = 'Hello, world!';
let encryptedData = encrypt(originalText);
console.log('Encrypted:', encryptedData.encryptedData);
let decryptedText = decrypt(encryptedData);
console.log('Decrypted:', decryptedText);
4. 使用 crypto
模块保护用户密码
为了安全地存储用户密码,通常的做法是将明文密码通过哈希算法进行哈希处理,并将哈希后的结果存储在数据库中。当用户登录时,输入的密码也会被哈希处理并与数据库中的哈希值进行比较。
const crypto = require('crypto');
// 哈希用户密码
function hashPassword(password) {
const salt = crypto.randomBytes(16).toString('hex');
const hash = crypto.pbkdf2Sync(password, salt, 100000, 64, 'sha512').toString('hex');
return { salt, hash };
}
// 验证用户密码
function verifyPassword(inputPassword, storedSalt, storedHash) {
const hash = crypto.pbkdf2Sync(inputPassword, storedSalt, 100000, 64, 'sha512').toString('hex');
return hash === storedHash;
}
// 示例用法
let password = 'password123';
let { salt, hash } = hashPassword(password);
console.log('Salt:', salt);
console.log('Hash:', hash);
// 验证密码
let isValid = verifyPassword('password123', salt, hash);
console.log('Password is valid:', isValid);
以上就是 Node.js 中 crypto
模块的一些基本用法。通过这些工具,我们可以更安全地处理数据,特别是在处理用户密码时。希望这对你有所帮助!
mark
Nice!
好文收藏下
不错啊,又是系列好文。
谢谢苏大大捧场啊,补完的已经发上来了 ,可惜没人气啊,唉~
好文就应该顶起,支持!!
看过文章有几个问题:
1.非对称加密只能使用Sign和Verify吗? 2.最后一段非对称的加密,我这里运行之后,加密都没内容,验证也不对。还有,看着Verify只能验证,没有解密的方法吗?
3.RSA加密的具体方法是什么那?
createHmac 第二个参数key 如果是一个字符窜应该怎么操作? crypto.createHmac(‘md5’,config.AppSecret);? 会提示TypeError: Not a string or buffer 新手求解答
科普文
解决了,crypto.createHmac(‘sha1’, app_secret).update(args).digest().toString(‘base64’); 这样的加密就是hmac-sha1的。之前是因为要加密的参数忘记排序的了。
Crypto 和 bcrypt 有什么区别呢?在cpu和内存上的优势,那个更好呢?
#又一次来看,留个赞#
楼主文章写得真好,赞
赞~
赞
经典,好文!!
赞~~mark
感谢分享, LZ 有密码学的书推荐么?
mark
很喜欢理论知识,感觉充实了自己
来自酷炫的 CNodeMD
收藏
好文,Mark
“之后A和B就分别用对方的公共密钥解密,用自己的私有密钥加密。” 这句有误吧?
是不是应该 “用对方的公钥加密,用自已的私钥解密”
好文,非常详细,虽然版本老点,仍值得参考。正在研究加密货币的加密解密技术,ebookcoin 的加密模块就是用的crypto,我会参考本文,写一篇应用项目实践篇,进一步消化学习。。
当然可以!以下是对“浅谈Nodejs中的Crypto模块”的详细回答,并附带一些示例代码。
浅谈Node.js中的Crypto模块
背景
Node.js 提供了一个内置的 crypto
模块,该模块用于进行各种加密操作。它可以用来生成哈希值、创建 HMAC、加密和解密数据、以及实现 SSL/TLS 安全通信等。
主要功能
- 哈希(Hashing): 用于生成数据的固定长度字符串表示。
- HMAC: 基于哈希函数的一种算法,提供了一种基于密钥的消息认证方法。
- 加密和解密: 使用对称或非对称算法来加密和解密数据。
- 证书管理: 可以生成和管理 X.509 证书。
示例代码
-
哈希生成
const crypto = require('crypto'); // 创建一个 SHA256 哈希对象 const hash = crypto.createHash('sha256'); // 更新哈希对象的数据 hash.update('Hello, World!'); // 获取哈希值 const result = hash.digest('hex'); console.log(result); // 输出: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
-
HMAC生成
const crypto = require('crypto'); // 创建一个 HMAC 对象 const hmac = crypto.createHmac('sha256', 'secretKey'); // 更新 HMAC 对象的数据 hmac.update('Hello, World!'); // 获取 HMAC 值 const result = hmac.digest('hex'); console.log(result); // 输出依赖于 secretKey 和输入数据
-
AES加密与解密
const crypto = require('crypto'); const algorithm = 'aes-256-cbc'; const key = crypto.randomBytes(32); const iv = crypto.randomBytes(16); function encrypt(text) { let cipher = crypto.createCipheriv(algorithm, Buffer.from(key), iv); let encrypted = cipher.update(text); encrypted = Buffer.concat([encrypted, cipher.final()]); return { iv: iv.toString('hex'), encryptedData: encrypted.toString('hex') }; } function decrypt({ iv, encryptedData }) { let ivBuffer = Buffer.from(iv, 'hex'); let encryptedBuffer = Buffer.from(encryptedData, 'hex'); let decipher = crypto.createDecipheriv(algorithm, Buffer.from(key), ivBuffer); let decrypted = decipher.update(encryptedBuffer); decrypted = Buffer.concat([decrypted, decipher.final()]); return decrypted.toString(); } const originalText = 'Hello, World!'; const encryptedData = encrypt(originalText); console.log('Encrypted:', encryptedData.encryptedData); console.log('Decrypted:', decrypt(encryptedData)); // 输出: Hello, World!
总结
crypto
模块提供了强大的加密功能,适合在应用中保护敏感信息,如密码和数据安全传输。通过哈希、HMAC 和 AES 加密,我们可以实现数据的安全存储和传输。实际开发中,建议使用安全可靠的密钥管理和哈希算法来增强安全性。
希望这些示例对你有所帮助!