【Node.js】crypto 模块

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

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

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

js 复制代码
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支持,但是需要自己封装好函数。

js 复制代码
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);
相关推荐
给力学长3 小时前
自习室预约小程序的设计与实现
java·数据库·vue.js·elementui·小程序·uni-app·node.js
有事没事实验室3 小时前
node.js中的path模块
前端·css·node.js·html·html5
该用户已不存在10 小时前
Node.js 真的取代了PHP吗?
前端·后端·node.js
牛马喜喜10 小时前
electron-vite 动态加载脚本 实现动态插件
electron·node.js
一个很帅的帅哥10 小时前
Webpack 和 Vite 的关键区别
前端·webpack·前端框架·node.js
sq80016 小时前
listr2 入门教程2-Node.js持续显示任务运行状态
node.js
koooo~1 天前
node.js中的fs与path模块
node.js
刘大猫.1 天前
npm ERR! cb() never called!
前端·npm·node.js·npm install·npmm err·never called
李先生9302 天前
Puppeteer最新迁移和服务
前端·node.js
FogLetter2 天前
SQLite3入门指南:轻量级数据库的奇妙冒险
后端·node.js