skip to Main Content

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


  1. looks like the key is to long. try to slice it like this:

    const key = crypto.createHash('sha256').update(secretKey).digest('hex').slice(0, 32);
    Login or Signup to reply.
  2. Try this, let me know how it goes. Checkout the if statement difference between mine and yours

    const crypto = require('crypto');
    
    function encrypt_decrypt(action, string) {
        let output = false;
        const encrypt_method = "aes-256-cbc";
        const secret_key = 'vdbdfbdfbdfbsvlksdhb';
        const secret_iv = '67b349vsdvbsdbsdd';
        // hash
        const key = crypto.createHash('sha256').update(secret_key, 'utf8').digest('hex');
        const iv = crypto.createHash('sha256').update(secret_iv, 'utf8').digest().slice(0, 16);
        
        
        if (action === 'encrypt') {
            const cipher = crypto.createCipheriv(encrypt_method, key, iv);
            output = cipher.update(string, 'utf8', 'base64');
            output += cipher.final('base64');
        } else if (action === 'decrypt') {
            const decipher = crypto.createDecipheriv(encrypt_method, key, iv);
            output = decipher.update(string, 'base64', 'utf8');
            output += decipher.final('utf8');
        }
        
        return output;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search