Skip to content
Advertisement

openssl_decrypt returns blank

I tried the following code

  <?PHP
    
       $encrypt_method = "AES-128-CBC";
        $secret_key = 'iuiuiui';
        $secret_iv = '1234567891234567';
        $string="keeri";
    
        // hash
        $key = hash('sha256', $secret_key);
        
        // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
        $iv = substr(hash('sha256', $secret_iv), 0, 16);
         $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
         
          echo "encrypt----)";
          echo $output ;
         
          echo "decrypt---";
           $output1 = openssl_decrypt($string, $encrypt_method, $key, 0, $iv);
           echo $output1;
         
    ?>

and getting the following output

encrypt----)3BR54C8qvhHG3e4Lgry4uw==decrypt----)

The decrypt string ($output1) is blank.

Advertisement

Answer

Your code is running well but the input data to your decrypt functionality is wrong.

You are feeding the openssl_decrypt function with the (original) plaintext and not with the data encrypted by openssl_encrypt (“output”).

Just a friendly information regarding the security of your code: as you are using the AES algorithm in mode “CBC” it is necessary to use a random generated initialization vector (“iv”) or your complete encryption gets vulnerable.

This will be the output of your encryption/decryption:

encrypt----)3BR54C8qvhHG3e4Lgry4uw==decrypt---keeri

complete code:

<?php
$encrypt_method = "AES-128-CBC";
$secret_key = 'iuiuiui';
$secret_iv = '1234567891234567';
$string="keeri";

// hash
$key = hash('sha256', $secret_key);

// iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
$iv = substr(hash('sha256', $secret_iv), 0, 16);
$output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);

echo "encrypt----)";
echo $output ;

echo "decrypt---";
//$output1 = openssl_decrypt($string, $encrypt_method, $key, 0, $iv);
$output1 = openssl_decrypt($output, $encrypt_method, $key, 0, $iv);
echo $output1;
?>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement