• 【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
  • 相关阅读:
    数据结构-顺序存储二叉树
    MFC Windows 程序设计[138]之黑白钢琴键(附源码)
    slf4j中如何进行log4j配置呢?
    Python笔记——linux/ubuntu下安装mamba,安装bob.learn库
    Python爬虫简介
    Allegro如何输出IDF文件操作指导
    idea由artifactId快速找到对应的maven依赖配置复制使用
    我的 React 最佳实践
    Java学习笔记(三)
    GitLab CI/CD的原理及应用详解(三)
  • 原文地址:https://blog.csdn.net/XiugongHao/article/details/133755804