node使用方法(使用的是node17版本,会出问题)
const crypto = require("node:crypto");
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"));
^
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'
}
解决办法,执行代码如下
const crypto = require("node:crypto");
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");
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);