使用npm“ crypto”模块的Node.js加密问题

时间:2019-04-04 13:49:22

标签: javascript node.js encryption cryptography

当我尝试加密或解密令牌时,出现此错误:

sudo apt-get install graphviz libgraphviz-dev pkg-config

我必须执行与此链接相同的加密:here

有人可以帮助我吗? :)

祝您有美好的一天!

这是我所做的:

internal/crypto/cipher.js:92
    this[kHandle].initiv(cipher, credential, iv, authTagLength);
                  ^

Error: Invalid IV length

1 个答案:

答案 0 :(得分:0)

您需要使用缓冲区或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&timestamp=1545735181'));
console.log('NodeJS decrypt: ', decrypt_token('hxdBZWB4eNn0lstyQU3cIX3WPj4ZLZu-C8qD02QEex8ahvMSMagFJnAGr2C16qMGsOLIcqypO8NX4Tn65DCrXGKrEL5i75tj6WoHGyWAzs0'));

请注意,您需要合并updatefinal的结果