【Node.js】crypto 模块

crypto模块的目的是为了提供通用的加密和哈希算法。用纯JavaScript代码实现这些功能不是不可能,但速度会非常慢。

Nodejs用C/C++实现这些算法后,通过cypto这个模块暴露为JavaScript接口,这样用起来方便,运行速度也快。

只要密钥发生了变化,那么同样的输入数据也会得到不同的签名,因此,可以把Hmac理解为用随机数“增强”的哈希算法。

const crypto = require('crypto');

// 创建哈希算法 md5, sha1等,以 md5 为例:
const hash = crypto.createHash('md5');
// Hmac 也是一种哈希算法,但它还需要一个密钥
const hmac = crypto.createHmac('sha256', 'secret-key');

// update 方法将一段字符进行哈希转换,可任意多次调用update():
hash.update('Hello, world!');
hash.update('Hello, nodejs!');
hmac.update('Hello, nodejs!');

// hex 以十六进制数据的形式进行展示,也可以使用 base64 格式进行展示
console.log(hash.digest('hex')); 
console.log(hmac.digest('base64'));

update()方法默认字符串编码为UTF-8,也可以传入Buffer。

AES是一种常用的对称加密算法,加解密都用同一个密钥。crypto模块提供了AES支持,但是需要自己封装好函数。

const crypto = require("crypto");
// 加密
function encrypt(key, iv, data) {
  let decipher = crypto.createCipheriv('aes-128-cbc', key, iv);
  // decipher.setAutoPadding(true);
  return decipher.update(data, 'binary', 'hex') + decipher.final('hex');
}
// 解密
function decrypt(key, iv, crypted) {
  crypted = Buffer.from(crypted, 'hex').toString('binary');
  let decipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
  return decipher.update(crypted, 'binary', 'utf8') + decipher.final('utf8');
}
// key, iv必须是16个字节
let key = '1234567890123456';
let iv = '1234567890123456';
let data = 'hello world';
let crypted = encrypt(key, iv, data);
console.log("加密结果",crypted);
let decrypted = decrypt(key, iv, crypted);
console.log("解密结果",decrypted);

你可能感兴趣的:(Node.js,node.js)