无法使用 Node.js(加密)解密 aes-256-cbc 加密负载

问题描述 投票:0回答:1

我可以使用 openssl 加密和解密字符串:

ENCRYPTED=$(echo "my_secret_data" | openssl aes-256-cbc -pass "pass:bab3fd92bcd7d464" -pbkdf2 -a -A)

echo -n $ENCRYPTED | base64 -d | openssl aes-256-cbc -d -pass "pass:bab3fd92bcd7d464" -pbkdf2

但是,我无法使用 Node.js 解密回字符串。

我尝试了以下 Node.js 代码:

const crypto = require('crypto');

const encryptedTextBase64 = 'U2FsdGVkX18AYE13z9uboo3WZhktr03EeV0WFA0MH4o=';
const password = 'bab3fd92bcd7d464';

// Decode the base64-encoded text
const encryptedText = Buffer.from(encryptedTextBase64, 'base64');

// Create a decipher object
const decipher = crypto.createDecipher('aes-256-cbc', password);

// Update the decipher with the encrypted text
let decrypted = decipher.update(encryptedText, 'binary', 'utf8');
decrypted += decipher.final('utf8');

console.log(decrypted);

但我收到错误

node:internal/crypto/cipher:199
  const ret = this[kHandle].final();
                            ^

Error: error:1C800064:Provider routines::bad decrypt
    at Decipher.final (node:internal/crypto/cipher:199:29)
    at Object.<anonymous> (.../decrypt.js:14:23)
    at Module._compile (node:internal/modules/cjs/loader:1256:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
    at Module.load (node:internal/modules/cjs/loader:1119:32)
    at Module._load (node:internal/modules/cjs/loader:960:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:86:12)
    at node:internal/main/run_main_module:23:47 {
  library: 'Provider routines',
  reason: 'bad decrypt',
  code: 'ERR_OSSL_BAD_DECRYPT'
}

但是以下 bash 代码可以按预期工作:

echo -n U2FsdGVkX18AYE13z9uboo3WZhktr03EeV0WFA0MH4o= | base64 -d | openssl aes-256-cbc -d -pass "pass:bab3fd92bcd7d464" -pbkdf2

非常感谢您提供有效的 Node.js 代码来解密有效负载的任何帮助。

如果 bash 命令也需要更改,那不是问题。我的最终目标是能够使用 bash 加密字符串并使用已知的密钥使用 Node.js 解密。

node.js bash openssl aes cryptojs
1个回答
0
投票

阅读@Topaco 的评论后,我可以想出一个工作代码:

const crypto = require('crypto');

const encryptedTextBase64 = 'U2FsdGVkX18AYE13z9uboo3WZhktr03EeV0WFA0MH4o=';
const password = 'bab3fd92bcd7d464';

// Decode the base64-encoded text
const encryptedText = Buffer.from(encryptedTextBase64, 'base64');

// Extract salt (first 8 bytes) and ciphertext (the rest)
const salt = encryptedText.slice(8, 16);
const ciphertext = encryptedText.slice(16);

// Derive the key and IV using PBKDF2
const keyIVBuffer = crypto.pbkdf2Sync(password, salt, 10000, 48, 'sha256');
const key = keyIVBuffer.slice(0, 32);
const iv = keyIVBuffer.slice(32);

// Create a decipher object with IV
const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);

// Update the decipher with the ciphertext
let decrypted = decipher.update(ciphertext, 'binary', 'utf8');
decrypted += decipher.final('utf8');

console.log(decrypted);
© www.soinside.com 2019 - 2024. All rights reserved.