当我尝试加密或解密令牌时,出现此错误:
internal/crypto/cipher.js:92
this[kHandle].initiv(cipher, credential, iv, authTagLength);
^
Error: Invalid IV length
我必须执行与此链接相同的加密:这里
有人可以帮助我吗? :)
祝大家有美好的一天!
这是我所做的:
var crypto = require('crypto'),
key = 'xNRxA48aNYd33PXaODSutRNFyCu4cAe/InKT/Rx+bw0=',
iv = '81dFxOpX7BPG1UpZQPcS6w==';
function encrypt_token(data) {
var cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
cipher.update(data, 'binary', 'base64');
return cipher.final('base64');
}
function decrypt_token(data) {
var decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
decipher.update(data, 'base64', 'binary');
return decipher.final('binary');
}
console.log('NodeJS encrypt: ', encrypt_token('partnerId=1&operationId=30215&clientId=CDX12345×tamp=1545735181'));
console.log('NodeJS decrypt: ', decrypt_token('hxdBZWB4eNn0lstyQU3cIX3WPj4ZLZu-C8qD02QEex8ahvMSMagFJnAGr2C16qMGsOLIcqypO8NX4Tn65DCrXGKrEL5i75tj6WoHGyWAzs0'));
您需要使用缓冲区或 utf8 字符串作为createCipheriv
的参数
这有效:
'use strict';
const crypto = require('crypto');
const key = Buffer.from('xNRxA48aNYd33PXaODSutRNFyCu4cAe/InKT/Rx+bw0=', 'base64');
const iv = Buffer.from('81dFxOpX7BPG1UpZQPcS6w==', 'base64');
function encrypt_token(data) {
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
const encryptedData = cipher.update(data, 'utf8', 'base64') + cipher.final('base64');
return encryptedData;
}
function decrypt_token(data) {
const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
const decripted = decipher.update(data, 'base64', 'utf8') + decipher.final('utf8');
return decripted;
}
console.log('NodeJS encrypt: ', encrypt_token('partnerId=1&operationId=30215&clientId=CDX12345×tamp=1545735181'));
console.log('NodeJS decrypt: ', decrypt_token('hxdBZWB4eNn0lstyQU3cIX3WPj4ZLZu-C8qD02QEex8ahvMSMagFJnAGr2C16qMGsOLIcqypO8NX4Tn65DCrXGKrEL5i75tj6WoHGyWAzs0'));
另请注意,您需要连接update
和final
的结果