openssl_decrypt没有按预期工作

时间:2018-03-16 04:12:45

标签: php encryption

我已经编写了两个函数来使用openssl加密和解密数据

如果我直接使用openssl_encrypt或者使用我的函数,我的testtring的返回值相同。

问题在于解密。只有在没有该函数的情况下直接使用openssl_encrypt,解密才有效。 如果我使用该函数来加密数据,我只会从解密中得到一个空的响应。

我的代码如下:

$key = base64_decode("PRIV KEY");
$cipher = "aes-256-gcm";
$iv = base64_decode("BASE64 encoded IV ");
$tag = base64_decode("BASE64 encoded TAG ");

function mc_encrypt($plaintext,$cipher, $key, $iv, $tag){
    $encrypted_text = openssl_encrypt($plaintext, $cipher, $key, $options=0, $iv, $tag);
    return $encrypted_text; 
}

function mc_decrypt($encrypted_text ,$cipher, $key, $iv, $tag){
    $decrypted_text = openssl_decrypt($encrypted_text, $cipher, $key, $options=0, $iv, $tag);
    return $decrypted_text; 
}

$test = "Teststring";

// Success Message is returned
$encrypted = openssl_encrypt($test, $cipher, $key, $options=0, $iv, $tag);
// Success Message is NOT returned
$encrypted = mc_encrypt($test, $cipher, $key, $iv, $tag);

$decrypted = mc_decrypt($encrypted, $cipher, $key, $iv, $tag);
if($decrypted == $test)
{
echo "Success!";
}

1 个答案:

答案 0 :(得分:0)

我知道这是一个古老的问题,但是如果有人遇到相同的问题,请尝试更改openssl_decrypt函数中的$ options参数,该参数将向您返回解密的数据。

例如,可以使用以下标志来完成OpenSSL中的解密:OPENSSL_ZERO_PADDING

openssl_decrypt($encrypted_text, $cipher, $key, OPENSSL_ZERO_PADDING, $iv);

而标志:OPENSSL_RAW_DATA主要用于加密openssl_encrypt中的纯文本

示例: openssl_encrypt($data, $cipher, $key, OPENSSL_RAW_DATA, $iv);