【问题标题】:Nodejs encryption problems with npm "crypto" modulenpm“crypto”模块的Nodejs加密问题
【发布时间】:2019-04-04 22:12:23
【问题描述】:

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

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

Error: Invalid IV length

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

有人可以帮助我吗? :)

祝你有美好的一天!

这是我所做的:

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&timestamp=1545735181'));
console.log('NodeJS decrypt: ', decrypt_token('hxdBZWB4eNn0lstyQU3cIX3WPj4ZLZu-C8qD02QEex8ahvMSMagFJnAGr2C16qMGsOLIcqypO8NX4Tn65DCrXGKrEL5i75tj6WoHGyWAzs0'));

【问题讨论】:

    标签: javascript node.js encryption cryptography


    【解决方案1】:

    createCipheriv需要使用buffer或utf8字符串作为参数

    这行得通:

    '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 的结果

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-02
      • 1970-01-01
      • 2013-02-09
      • 2019-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-23
      相关资源
      最近更新 更多