Openssl_encrypt, key openssl_decrypt, iv

According to the documentation OpenSSL

( https://www.openssl.org/docs/apps/enc.html#OPTIONS ) they expect values hex-digit

for key

and iv

; does this only mean numbers? or will there be a hash md5

? (Since a md5

doesn't seem to be reversible)

  • Note that I mention key

    and iv

    because $password

    in a function is PHP

    openssl_encrypt

    actually a key.

(Almost) straight from the PHP

comments ( http://php.net/manual/en/function.openssl-encrypt.php )

function strtohex($x) 
{
    $s='';
    foreach (str_split($x) as $c) $s.=sprintf("%02X",ord($c));
    return($s);
} 

$source = 'It works !';

$iv = substr( md5( "123sdfsdf4567812345678" ), 0, 16 );
$pass = '1234567812345678';
$method = 'aes-256-cbc';

echo "\niv in hex to use: ".$iv;
echo "\nkey in hex to use: ".strtohex($pass);
echo "\n";

file_put_contents ('./file.encrypted',openssl_encrypt ($source, $method, $pass, true, $iv));

$exec = "openssl enc -".$method." -d -in file.encrypted -nosalt -nopad -K ".strtohex($pass)." -iv ".$iv;

echo 'executing: '.$exec."\n\n";
echo exec ($exec);
echo "\n";

      

+3


source to share


1 answer


Your first link is about command line tools, not PHP functions. You would have a tricky time throwing binary data into the terminal, hence the key must be hex encoded.

However, in PHP openssl_encrypt()

it openssl_decrypt()

expects a raw binary string.

The documentation is also misleading as it mentions "password" instead of "key". You noticed this, but the encryption key is not something that you have to simply enter from the keyboard, but md5()

something else is never the answer to the encryption key. The key should be generated randomly through openssl_random_pseudo_bytes()

(or at least the most convenient way for your case):

$key = openssl_random_pseudo_bytes(32);

      

(the same applies to IV)



If you need to hex encode the received one $key

, just pass it in bin2hex()

, but the example you gave is a bit broken ... you are doing double encryption. Encrypting the contents of a file via PHP is enough, you don't need to deal with the command line.

Please note that my answer is not the whole story about encryption. You should also add authentication, correct padding, think carefully about how to manage and store your keys, etc.

If you want to know about it, here's a fairly short but still descriptive blog post that gives the correct answers to the key points you should cover: http://timoh6.github.io/2014/06/16/PHP- data-encryption-cheatsheet.html

If you just need to get the job done - use the popular encryption library, don't write your own.

+3


source







All Articles