使用node中的crypto进行加解密

node使用方法(使用的是node17版本,会出问题)

// 加密解密
const crypto = require("node:crypto");

/**
 * 接受三个参数
 * 1 algorithm 接收一个算法 aes-256-cbc
 * 2 key 也就是密钥 32位
 * 3 iv 初始化向量,支持16位,保证我们生成的密钥串每次都是不一样的,密钥串缺少位数,还可以进行补齐
 */

const algorithm = "aes-256-cbc";

const key = crypto.randomBytes(32);

const iv = Buffer.from(crypto.randomBytes(16));

const cipher = crypto.createCipheriv(algorithm, key, iv);

cipher.update("this is a success", "utf-8", "hex");

// 接收密文

const result = cipher.final("hex");

console.log("result:", result);

// 解密操作

const de = crypto.createDecipheriv(algorithm, key, iv);

de.update(result, "hex", "utf-8");

console.log("解密:", de.final("utf-8"));

// node xxx.js执行会报错如下:const ret = this[kHandle].final();
                            ^
Error: error:1C800064:Provider routines::bad decrypt
    at Decipheriv.final (node:internal/crypto/cipher:199:29)
    at Object.<anonymous> (/Users/yxuser/Desktop/github上的代码/nodeDemo/index.js:69:23)
    at Module._compile (node:internal/modules/cjs/loader:1256:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
    at Module.load (node:internal/modules/cjs/loader:1119:32)
    at Module._load (node:internal/modules/cjs/loader:960:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:23:47 {
  library: 'Provider routines',
  reason: 'bad decrypt',
  code: 'ERR_OSSL_BAD_DECRYPT'
}

解决办法,执行代码如下

// 加密算法修改为 aes-256-gcm

// 加密解密
const crypto = require("node:crypto");

/**
 * 接受三个参数
 * 1 algorithm 接收一个算法 aes-256-cbc
 * 2 key 也就是密钥 32位
 * 3 iv 初始化向量,支持16位,保证我们生成的密钥串每次都是不一样的,密钥串缺少位数,还可以进行补齐
 */

const algorithm = "aes-256-gcm";

const key = crypto.randomBytes(32);

const iv = Buffer.from(crypto.randomBytes(16));

const cipher = crypto.createCipheriv(algorithm, key, iv);

let encryptedData = cipher.update("this is a success", "utf-8", "hex");

// 接收密文

encryptedData += cipher.final("hex");

const authTag = cipher.getAuthTag().toString("hex"); // <- new

console.log("result:", { authTag, encryptedData });

// 解密操作

const de = crypto.createDecipheriv(algorithm, key, iv);

de.setAuthTag(Buffer.from(authTag, "hex"));

let decData = de.update(encryptedData, "hex", "utf-8");

decData += de.final("utf-8");

console.log("解密:", decData);
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值