模块概述:
- crypto 模块的目的是为了提供通用的加密哈希算法(如用纯js编写,速度会很慢),该模块是使用 C/C++实现的。
- crypto 是Node.js 的核心模块,它提供了安全相关的功能,如摘要运算、加密、电子签名等。
摘要(hash):
摘要(digest): 将长度不固定的消息作为输入,通过运行hash函数,生成固定长度的输出,这段输出即为摘要。
作用及特点:
- 通常用于验证消息完整、未被篡改
- 输入固定的情况下,产生固定的输出。但知道输出的情况下,无法反推出输入
常见的摘要算法及对应输出位数:
- MD5: 128位
- SHA-1: 160位
- SHA256: 256位
- SHA512: 512位
const crypto = require('crypto');// createHash的参数还可以传入 SHA-1、SHA256、SHA512const hash = crypto.createHash('md5');// 可以任意多次调用 update();hash.update('Hello, World');hash.update('Hello, Nodejs');// 输出的是 16进制console.log(hash.digest('hex'));
update() 方法默认字符串编码为 UTF-8,也可以传入 Buffer。
备注: 摘要、hash、散列这几个词大部分时间指的都是一样的。
**
MAC - HMAC(MAC的实现形式)
- MAC(Message Authentication Code): 消息认证码,用以保证数据的完整性。运算结果取决于消息本身、密钥。
- MAC可以有多种不同的实现方式,比如HMAC。
- HMAC(Hash-based Message Authentication Code): 可以理解为带密钥的 hash 函数
const crypto = require('crypto');const hmac = crypto.createHmac('sha256', 'secret-key');hmac.update('Hello, world!');hmac.update('Hello, nodejs!');console.log(hmac.digest('hex'));
只要密钥发生变化,那么同样的输入数据也会得到不同的签名,因此可以把 HMAC 理解为用随机数“增强”的哈希算法
**
对称加密、非对称加密
对称加密
- 加密、解密所用的密钥是相同的
- 常见的对称加密算法: DES、3DES、AES、Blowfish、RC5、IDEA
encryptedText = encrypt(plainText, key); // 加密 plainText = decrypt(encryptedText, key); // 解密
AES
const crypto = require('crypto');// 加密function aesEncrypt(data, key) {const cipher = crypto.createCipher('aes192', key);var crypted = cipher.update(data, 'utf8', 'hex');crypted += cipher.final('hex');return crypted;}// 解密function aesDecrypt(encrypted, key) {const decipher = crypto.createDecipher('aes192', key);var decrypted = decipher.update(encrypted, 'hex', 'utf8');decrypted += decipher.final('utf8');return decrypted;}var data = 'Hello, this is a secret message!';var key = 'Password!';var encrypted = aesEncrypt(data, key);var decrypted = aesDecrypt(encrypted, key);console.log('Plain text: ' + data);console.log('Encrypted text: ' + encrypted);console.log('Decrypted text: ' + decrypted);
注:
AES有很多不同的算法,如 aes192、aes-128-ecb、aes-256-cbc等
RSA
非对称加密算法,即一个私钥和一个公钥构成的密钥对,通过私钥加密,公钥解密,或者通过公钥加密,私钥解密。其中,公钥可公开,私钥必须保密
- 常见的非对称加密算法:RSA、DSA、ElGamal
