i am new to node js here is my php function can anyone help me to convert this on nodejs.
function encrypt_decrypt($action, $string) {
$output = false;
$encrypt_method = "AES-256-CBC";
$secret_key = 'vdbdfbdfbdfbsvlksdhb';
$secret_iv = '67b349vsdvbsdbsdd';
// hash
$key = hash('sha256', $secret_key);
$iv = substr(hash('sha256', $secret_iv), 0, 16);
if ( $action == 'encrypt' ) {
$output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
$output = base64_encode($output);
} else if( $action == 'decrypt' ) {
$output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
}
return $output;
}
This is what i tried but it throws this error RangeError: Invalid key length
. Here is my node.js code
const crypto = require('crypto');
const encryptDecrypt = (action, string) => {
const output = false;
const encryptMethod = 'AES-256-CBC';
const secretKey = '3752395n39572395m82219vc5b13';
const secretIv = '67b349vm13408vm2035983v6n2390';
const key = crypto.createHash('sha256').update(secretKey).digest('hex');
const iv = crypto.createHash('sha256').update(secretIv).digest('hex').slice(0, 16);
if (action === 'encrypt') {
output = crypto.createCipheriv(encryptMethod, key, iv).update(string).digest('base64');
} else if (action === 'decrypt') {
output = crypto.createDecipheriv(encryptMethod, key, iv).update(string).digest('utf8');
}
return output;
};
const result = encryptDecrypt('encrypt', 'This is a secret message');
console.log(result);
2
Answers
looks like the key is to long. try to slice it like this:
Try this, let me know how it goes. Checkout the if statement difference between mine and yours