When I try to encrypt or decrypt a token, I have this error :
internal/crypto/cipher.js:92
this[kHandle].initiv(cipher, credential, iv, authTagLength);
^
Error: Invalid IV length
I have to do the same encryption that's done on this link : here
Can someone help me ? :)
Have a great day all !
Here is what i've done:
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'));
You need to use buffer or utf8 strings as parameters for createCipheriv
.
This works:
'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-cbc', 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'));
Note also that you need to concat the results of update
and final
.