簡體   English   中英

如何在nodejs中用aes-128-cbc算法解密php加密的字符串?

[英]How to decrypt string in nodejs that encrypted in php with aes-128-cbc algorithm?

我需要加密字符串,用這個加密的字符串發送 http 請求,然后在 nodejs 服務器中解密它。

Php 方:

$var  = openssl_encrypt('string', "aes-128-cbc", 'stringstringstri');

節點端:

let decipher = crypto.createDecipher('aes-128-cbc', 'stringstringstri');
let decrypted = decipher.update(encrypted, 'utf8', 'utf8') + decipher.final('utf8');

也試過

const initVector = crypto.randomBytes(32);
const decipher = crypto.createDecipheriv('aes-128-cbc', 'stringstringstri', initVector)
let decryptedData = decipher.update(encrypted, 'utf8', 'utf-8')
decryptedData += decipher.final('utf-8');

並收到錯誤: wrong final block lengththis[kHandle].initiv(cipher, credential, iv, authTagLength); TypeError: Invalid initialization vector this[kHandle].initiv(cipher, credential, iv, authTagLength); TypeError: Invalid initialization vector

由於您沒有在 PHP 中傳遞任何iv ,因此它使用默認的iv ,它是一個空字符串。 因此,您也需要在 Node.js 中考慮這一點。

所以變化是這樣的:

const key = 'string';
const cipher = crypto.createDecipheriv('aes-128-cbc', key, Buffer.alloc(16));
const cipherEncrypted = Buffer.from(encrypted, 'base64');
const decrypted = Buffer.concat([cipher.update(cipherEncrypted), cipher.final()]);
console.log(decrypted.toString());

你能實施像這篇文章建議的東西嗎? https://ashish-dhodare.medium.com/implementing-aes-cbc-encryption-in-node.js-java-and-c-cross-language-encryption-42d1844119b9


function encrypt(plainString, AesKey, AesIV) {
    const cipher = crypto.createCipheriv("aes-128-cbc", AesKey, AesIV);
    let encrypted = Buffer.concat([cipher.update(Buffer.from(plainString, "utf8")), cipher.final()]);
    return encrypted.toString("base64");
}

function decrypt(base64String, AesKey, AesIV) {
    const decipher = crypto.createDecipheriv("aes-128-cbc", AesKey, AesIV);
    const deciphered = Buffer.concat([decipher.update(Buffer.from(base64String, "base64")), decipher.final()]);
    return deciphered.toString("utf8");
}

// const key = crypto.randomBytes(32); //Need 32 bytes (256 bits) key as we are using AES-256 encryption
const key = Buffer.from("J/PYjc1ftDFK5+77U1PB80v2TamokGap5yCIP2YI6tQ=", "base64");
// const iv = crypto.randomBytes(16); //Need 16 bytes (128 bits) Initialization vector as default block size is 128 bits
const iv = Buffer.from("gaOr3uvhZEwFeSbRHwlHcg==", "base64");

// Its better to pass iv and key in bytes/buffer
var encryptedData = encrypt("some data to encrypt", key, iv);
console.log(encryptedData);
// Need same key and iv for decryption otherwise it won't work
var decryptedData = decrypt(encryptedData, key, iv)
console.log(decryptedData);```

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM