crypto(加密)
- crypto 模块提供了加密功能,包括对 OpenSSL 的哈希、HMAC、加密、解密、签名、以及验证功能的一整套封装。
- crypto模块的目的是为了提供通用的加密和哈希算法。用纯JavaScript代码实现这些功能不是不可能,但速度会非常慢。Nodejs用C/C++实现这些算法后,通过cypto这个模块暴露为JavaScript接口,这样用起来方便,运行速度也快。
- 使用
const crypto=require('crypto');
来访问该模块。
MD5和SHA1
MD5是一种常用的哈希算法,用于给任意数据一个“签名”。这个签名通常用一个十六进制的字符串表示。
const crypto=require('crypto');//先引入加密内置模块
//第一种方式
const hash=crypto.createHash('md5');
hash.update('hello world');
console.log(hash.digest('hex'));
//第二种方式:链式
const hash1 = crypto.createHash('md5')
.update('hello world')
.digest('hex');
console.log(hash1);
加密算法不同,强度也不一样,下面是sha1加密 :
const hash=crypto.createHash('sha1');
hash.update('hello world');//更新处理
console.log(hash.digest('hex'));
Hmac
Hmac算法也是一种哈希算法,它可以利用MD5或SHA1等哈希算法。不同的是,Hmac还需要一个密钥;
只要密钥发生了变化,那么同样的输入数据也会得到不同的签名,因此,可以把Hmac理解为用随机数“增强”的哈希算法。
const crypto=require('crypto');//先引入加密内置模块
// 加密方式sha256,'secret-key'是密钥(非对称)
const hash = crypto.createHmac('sha256', 'secret-key');
hash.update('hello world');
console.log(hash.digest('hex'));
AES
对称加密算法,加密和解密都用相同的秘钥。
const crypto=require('crypto');//先引入加密内置模块
var data='hello world';//需要加密的内容
var key='secret key';//密钥其实不会直接给,从第三方的文件拿到key
// 数据加密
function aesEncrypt(data,key){
// 用指定的算法和密钥,返回一个cipher对象
const cipher=crypto.createCipher('aes192',key);
var crypted=cipher.update(data,'utf8','hex');//hex 16进制方式输出
crypted+=cipher.final('hex');//最终处理所有数据,以16进制形式输出
return crypted;
}
// 数据解密
function aesDecrypt(encrypted,key){
// 解密的算法、密钥要与加密的一样
const decipher=crypto.createDecipher('aes192',key);
var decrypted=decipher.update(encrypted,'hex');//输入的类型与输出的一致
decrypted+=decipher.final('utf8');//编码格式,输出utf-8格式
return decrypted;
}
// 调用加密方法
var encrypted=aesEncrypt(data,key);//输入原内容和密钥
console.log("encrypted:",encrypted);
// 调用解密方法
var decrypted=aesDecrypt(encrypted,key);//输入加密内容和密钥
console.log("decrypted:",decrypted);