是在小程序云函数本地调试时发生的。云端是否会出现乱码暂未测试,估计也会有。像上面这样,去掉了后面那一串是可以正常使用的,代码如下,其中使用的数据结构是跟官方文档一致的
let key = crypto.createDecipheriv('aes-256-gcm', “v3api密钥”, new Buffer.from(data[0].encrypt_certificate.nonce))
.update(data[0].encrypt_certificate.ciphertext,'base64','utf-8')
console.log(key) //输出后,末尾出现乱码
少了aad参数,云端可尝试 wechatpay-axios-plugin npm包
aes.decrypt(nonce, secret, ciphertext, aad)
/**
* Decrypts ciphertext.
*
* @param {string} iv - The initialization vector, 16 bytes string.
* @param {string} key - The secret key, 32 bytes string.
* @param {string} ciphertext - Base64-encoded ciphertext.
* @param {string} aad - The additional authenticated data, maybe empty string.
*
* @returns {string} Utf-8 plaintext.
*/
static decrypt(iv, key, ciphertext, aad = '') {
const buf = Buffer.from(ciphertext, base64)
const tag = buf.slice(-BLOCK_SIZES)
const payload = buf.slice(0, -BLOCK_SIZES)
const decipher = crypto.createDecipheriv(
algorithm, key, iv
).setAuthTag(tag).setAAD(Buffer.from(aad))
return Buffer.concat([
decipher.update(payload, hex),
decipher.final()
]).toString(utf8)
}