简体   繁体   中英

PHP openssl_encrypt and openssl_decrypt aes-256-gcm not work if inside function

I'm doing test with php openssl_encrypt and openssl_decrypt in a simple script without having the 2 inside any function but as soon I put the openssl_encrypt one inside a custom function that it's not working and there's no clear error string returns. Just have no clue what's the issue. I've attached the sample.

So if I comment out openssl_encrypt line and use encrypt() then it's not working but if put back openssl_encrypt then it works again. Any idea what's the issue when I use encrypt()?

$algo = 'aes-256-gcm';
$options = 0;
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($algo));
$key  = '13123123123';
$data = 'test';
$tag = null;
//$ciphertext = openssl_encrypt($data, $algo, $key, $options, $iv, $tag);
$ciphertext = encrypt($data, $algo, $key, $options, $iv, $tag);
$decrypt = openssl_decrypt($ciphertext, $algo, $key, $options , $iv, $tag);
if (false === $decrypt) {
    echo sprintf("OpenSSL error: %s", openssl_error_string()."\n");
}
echo "data:$data\n";
echo "decrypt:$decrypt\n";
printf ("Decryption %s\n", $data === $decrypt ? 'Ok' : 'Failed');

function encrypt($data, $algo, $key, $options, $iv, $tag) {
    return openssl_encrypt($data, $algo, $key, $options, $iv, $tag);
}

In the function signature of openssl_encrypt you see that $tag is passed as a reference ( &$tag ), but you dont do it.

The following works:

function encrypt($data, $algo, $key, $options, $iv, &$tag) {
    return openssl_encrypt($data, $algo, $key, $options, $iv, $tag);
}
$random_key= openssl_random_pseudo_bytes(16); $iv=bin2hex($random_key);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM