OpenSSL PHP to JavaScript (node)

By : enyo

I am converting an encryption script from PHP to JavaScript and am struggling...

The node.js cipher documentation is as follows:

crypto.createCipheriv(algorithm, key, iv)
Creates and returns a cipher object, with the given algorithm, key and iv.

The PHP openssl-encrypt documentation:

string openssl_encrypt ( string $data , string $method , string $password [, bool $raw_output = false [, string $iv = "" ]] )

PHP uses a password and and iv. Node only uses a password when no IV is used, otherwise you have to provide a key and an iv.

How would I convert my PHP function to node, when I'm using both, the password and iv.

I'm also unclear on what exactly the key represents... the node documentation states that the key and iv are calculated if only a password is provided.. is this what PHP does? If so, what does it do when I provide a password and an iv? Does it use the password as key?

By : enyo

From user comments in the PHP documentation, it seems the $password parameter in PHP is actually the encryption key, and not an actual password. This seems consistent with OpenSSL docs, which state that you use either a key and initialization vector, or use a password from which the key and IV are algorithmically derived, but you never provide a password and IV together.


<?php echo openssl_encrypt('foobar', 'aes-256-cbc', 'password', false, 'abcdefghijklmnop');
// prints CUigVN+6jU24E2FdfmmmTw==

echo -n foobar | openssl enc -aes-256-cbc -e -K 70617373776F7264 -iv 6162636465666768696A6B6C6D6E6F70 -nosalt -a
// prints CUigVN+6jU24E2FdfmmmTw==

The gotcha is probably that you need to provide the key and IV to openssl in hexadecimal.

By : lanzz

This video can help you solving your question :)
By: admin