0

I need to encrypt data in PHP and decrypt in Node.js.

I encrypt this in PHP:

$encrypt_method = "AES-256-CBC";
$secret_key = '7CEsPlLfVXcHf2S4wsnPnfNqYa+N/D/1zCXExN4aJSs=';
$secret_iv = 'StqUaIcbO9LFZ9QiuguXR6M/BepqZDV8p1now0FA/C4=';
// hash
$key = hash('sha256', $secret_key);

// iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
$iv = substr(hash('sha256', $secret_iv), 0, 16);
$output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
$output = base64_encode($output);

result:

VU5pckRaWHA4bjNaUjU3dGhscys3QT09

And decrypt in Node.js:

var crypto = require("crypto");
const decrypt = (textBase64, keyBase64, ivBase64) => {
    const algorithm = 'AES-256-CBC';
    const ivBuffer = Buffer.from(ivBase64, 'base64');
    const keyBuffer = Buffer.from(keyBase64, 'base64');

    const decipher = crypto.createDecipheriv(algorithm, keyBuffer, ivBuffer);
    decipher.setAutoPadding(false);

    let decrypted = decipher.update(textBase64, 'base64', 'utf8');
    decrypted += decipher.final('utf8');
    return decrypted;
}

const encryptedMessage = 'VU5pckRaWHA4bjNaUjU3dGhscys3QT09';
const key = '7CEsPlLfVXcHf2S4wsnPnfNqYa+N/D/1zCXExN4aJSs=';
const iv = Buffer.from('StqUaIcbO9LFZ9QiuguXR6M/BepqZDV8p1now0FA/C4=', 'base64').slice(0, 16);

// the message comes from the bytes AFTER the IV - this is what you should decrypt
const message = Buffer.from(encryptedMessage, 'base64').slice(16);

const result = decrypt(message, key, iv);

res.send("Decrypted: " + result);

Error: error:0606508A:digital envelope routines:EVP_DecryptFinal_ex:data not multiple of block length

I do not understand the error message, help to make a working example.

jps
  • 20,041
  • 15
  • 75
  • 79
Pastukhov
  • 11
  • 4
  • Your `entryptedMessage` has been twice converted to Base 64, is it normal ? Also, have you read this question : https://stackoverflow.com/questions/19934422/encrypt-string-in-php-and-decrypt-in-node-js ? – Seblor Dec 18 '19 at 14:16
  • php code does not extract bin data from base64 but node.js does. also your node.js code misses php's step to hash('sha256', ivBuffer).slice(0,16) . Also use OPENSSL_ZERO_PADDING instead of zero in _openssl_encrypt_ – Maxim Sagaydachny Dec 18 '19 at 15:10

0 Answers0