node.js - Encrypt in node and decrypt in PHP 7 with openssl
804
I found this post how to encrypt in php and decrypt in node and it works: Encrypt in PHP 7 decrypt in Node JS
But I have problem to do the same in oposite direction.
I tried like this:
Node:
const crypto = require('crypto');
const data = "data to encrypt";
const key = "315a5504d921f8327f73a356d2bbcbf1";
const iv = new Buffer(data.substring(0, 32), 'hex');
const cipher = crypto.createCipher('aes-256-cbc', key, iv);
let crypted = cipher.update(data, 'utf8', 'hex')
crypted += cipher.final('hex');
console.log(crypted);
PHP:
<?php
$encryptedMessage = '3aa3fc237aaf34a26482674cfcef1210';
$encryptionMethod = 'aes-256-cbc';
$secretHash = "315a5504d921f8327f73a356d2bbcbf1";
//To Decrypt
$iv_size = openssl_cipher_iv_length($encryptionMethod);
$iv = hex2bin(substr($encryptedMessage, 0, $iv_size * 2));
$decryptedMessage = openssl_decrypt(substr($encryptedMessage, $iv_size * 2), $encryptionMethod, $secretHash, 0, $iv);
echo "Decrypted: $decryptedMessage";
But not working, any idea how to make this work?
Answer
Solution:
The IV should be random and the same IV needs to be used in both the encryption and decryption process.
Your initialization vector is based on the unecrypted string, which is a very bad idea as you'd be leaking part of your unecrypted data if you send the IV with the encrypted data.