• 【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'));
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    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);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
  • 相关阅读:
    Git 详细教程之六:Git 命令总结(基本命令/GitHub/Gitee)
    Spring事件机制之ApplicationEvent
    【C++14算法】make_unique
    俄罗斯方块小游戏
    1-图像读取
    C语言经典100例题(56-60)--画圆;画方;画线
    【21天学习挑战赛—经典算法】冒泡排序
    期待重磅升级的梅李大梦想城亲子游乐园!第三代黄桥大梦想城先让你一饱眼福!
    OpenCV实战之人脸美颜美型算法
    云链商城连锁门店新零售O20系统以零售商城
  • 原文地址:https://blog.csdn.net/XiugongHao/article/details/133755804