I have an old PHP project which I am converting to Node JS. The PHP project had AES-256-CBC encryption and decryption method which I want to use in Node JS too.
PHP
<?php
function encrypt($plain_text) {
$method = 'aes-256-cbc';
$key = 'crocodile';
$iv = chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0);
$encrypted = base64_encode(openssl_encrypt($plain_text, $method, $key, OPENSSL_RAW_DATA, $iv));
return $encrypted;
}
function decrypt($encryptedMessage){
$method = 'aes-256-cbc';
$key = 'crocodile';
$iv = chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0);
$decrypted = openssl_decrypt(base64_decode($encryptedMessage), $method, $key, OPENSSL_RAW_DATA, $iv);
return $decrypted;
}
?>
NODE JS
var crypto = require('crypto');
var encrypt = function (plain_text) {
var encryptionMethod = 'AES-256-CBC';
var secret = "crocodile";
var iv = crypto.randomBytes(16);
var encryptor = crypto.createCipheriv(encryptionMethod, secret, iv);
return encryptor.update(plain_text, 'utf8', 'base64') + encryptor.final('base64');
};
var decrypt = function (encryptedMessage) {
var encryptionMethod = 'AES-256-CBC';
var secret = "crocodile";
var iv = crypto.randomBytes(16);
var decryptor = crypto.createDecipheriv(encryptionMethod, secret, iv);
return decryptor.update(encryptedMessage, 'base64', 'utf8') + decryptor.final('utf8');
};
The Node JS code is mostly copied from this answer: https://stackoverflow.com/a/28181444/6699134
The problem is that node js requires a 32 character secret key and I am not sure why it worked in PHP with only 9 letter secret key. Currently this node js code throws error: Invalid key length - which is obvious that it requires 32 character key. Any help will be greatly appreciated