php – how to do the same Nodejs crypto aes encryption CTR in PHP7?-ThrowExceptions

Exception or error:

so here is the nodejs code that i took from internet.

// Nodejs encryption with CTR
var crypto = require('crypto'),
    algorithm = 'aes-128-ofb',
    password = 'password12';

function encrypt(text){
  var cipher = crypto.createCipher(algorithm,password)
  var crypted = cipher.update(text,'utf8','hex')
  crypted += cipher.final('hex');
  return crypted;
}

function decrypt(text){
  var decipher = crypto.createDecipher(algorithm,password)
  var dec = decipher.update(text,'hex','utf8')
  dec += decipher.final('utf8');
  return dec;
}

var hw = encrypt("hello world")
// outputs hello world
console.log(decrypt(hw));

its working fine

but when i try decrypt it with openssl_decrypt in php7 i got wrong/different result.

can someone help?

How to solve:

The reason the PHP code is not giving you the answer you expect is that crypto.createCipher uses another function to derive a key and initialization vector (iv) from the supplied password.

The function in question is EVP_BytesToKey.

Below is the PHP code that will decrypt your ciphertext. I’ve also included an encrypt function so you can encrypt in the same manner in PHP.

function EVP_BytesToKey($data, $count, $cipher, $hashMethod) {
    $iv_length  = openssl_cipher_iv_length($cipher);
    $key_length = $iv_length; // This assumption may not always be true...
    $result = "";
    $digestInput = "";
    while(strlen($result) < ($key_length + $iv_length)) {
        $digestInput .= $data;
        $digest = openssl_digest($digestInput, $hashMethod);
        for ($iteration = 1; $iteration < $count; $iteration++) {
            $digest = openssl_digest(hex2bin($digest), $hashMethod);
        }
        $digestInput = hex2bin($digest);
        $result .= hex2bin($digest);
    }
    return (object)["key" => substr($result, 0, $key_length), "iv" => substr($result, $key_length, $iv_length)];
}

function decrypt($encryptedHex, $cipher, $password) {
    $encrypted = hex2bin($encryptedHex);
    $evp = EVP_BytesToKey($password, 1, $cipher, "md5");
    return openssl_decrypt($encrypted, $cipher, $evp->key, OPENSSL_RAW_DATA, $evp->iv);
}

function encrypt($plainText, $cipher, $password) {
    $evp = EVP_BytesToKey($password, 1, $cipher, "md5");
    return bin2hex(openssl_encrypt($plainText, $cipher, $evp->key, OPENSSL_RAW_DATA, $evp->iv));
}

$algorithm = "aes-128-ofb";
$password = "password12";
$encryptedHex = "f2211645785e4232339a0d";

echo "Ciphertext (hex): " . $encryptedHex . "\n";
echo "Plaintext: " . decrypt($encryptedHex, $algorithm, $password);

Leave a Reply

Your email address will not be published. Required fields are marked *