首页 > 解决方案 > 用于加密/解密的 NodeJS 加密

问题描述

我正在使用以下代码在 ColdFusion 中生成一些加密数据的数据库:

key = "nQw7y6QejwGFh/SNrul20Q==";
encrypt(myText, key, "AES/CBC/PKCS5Padding", "HEX");

它会生成一个加密字符串,例如:6F795025756EC54D60808EA98AC163D9143C2FCFEC1065FCCAB7AB0CD577E535. 我可以使用下面的代码对其进行解密

我设法创建了我的 NodeJS 类来解密这些数据。

const crypto = require('crypto');

const key = Buffer.from('nQw7y6QejwGFh/SNrul20Q==', 'base64');  

module.exports = class Encrypt {

    decryptText(text) {
        try {
            const ivCiphertext = Buffer.from(text, 'hex');
            const iv = ivCiphertext.slice(0, 16);
            const ciphertext = ivCiphertext.slice(16);
            var decipher = crypto.createDecipheriv('AES-128-CBC', key, iv);
            var value = 
                decipher.update(ciphertext, '', 'utf8') +
                decipher.final('utf8');
            return value;
        } catch (err) {
            console.log(err);
        }
    }
};

我试图在这个类中创建一个加密方法,以与在 ColdFusion 中生成的相同格式加密数据。

   encrypt(text) {
        const iv = crypto.randomBytes(16);
        let cipher = crypto.createCipheriv( 
            'AES-128-CBC', key, iv);
        let encrypted = cipher.update(text);
        encrypted = Buffer.concat([encrypted, cipher.final()]); 
        return encrypted.toString('hex');
    }

我做了以下测试:

const encrypt = new Encrypt();
const test = encrypt.encrypt('803315808');
console.log(test);
console.log(encrypt.decryptText(test));

第一个日志:

fdcec1c7098c0fc91a11ada1e849b543 

第二个日志:

Error: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length

标签: node.jsencryption

解决方案


推荐阅读