[英]openssl_decrypt () function not working, returning null
我使用openssl_encrypt和openssl_decrypt函数,但解密部分没有返回任何值,而使用相同的密钥加密工作正常。 这是我使用的功能。 变量$decrypted
总是返回null。 每一个小帮助将不胜感激
function deCryption($value)
{
$methods = openssl_get_cipher_methods();
$clefSecrete = "flight";
echo '<pre>';
foreach ($methods as $method) {
//$encrypted = openssl_encrypt($texteACrypter, $method, $clefSecrete); ----this was used for encryption
$decrypted = openssl_decrypt($value, $method, $clefSecrete);
echo "value=".$decrypted;
echo $method . ' : '. $decrypted . "\n";
break;
}
echo '</pre>';
return $decrypted;
}
我有完全相同的问题,然后用Google搜索我的问题并最终在这里,就我提出的同样问题。 所以我不得不在别处搜索。
我发现这篇文章有助于解释官方php文档的缺点。 另一篇内容相似的文章就在这里 。
最后它归结为密钥/密码。 openssl_encrypt库所期望的是密钥而不是密码。 密钥的大小必须是密码的内部密钥大小。 第一篇文章说如果你提供一个更长的密钥,那么多余的密钥就被丢弃了,一个比预期更短的密钥用零填充,即\\ x00字节。 我没有测试过这个事实。
我已编辑您的代码,如下所示。
我使用的想法是,密码所期望的初始向量的大小也是它期望的密钥的大小。 所以在这里,我正在传递密钥而不是密码。 只需找到将密码转换为密钥的方法。
在您的代码中,您没有传递选项和iv(初始化向量)。
iv是加密前密码与明文“混合”的字符串。 那么密码加密的是这种'混合'。 这很重要吗? 是! 没有这种“混合”,一对相同的明文就会形成一对相同的密文,这会导致攻击; 如果两个相同的明文 - 密文对不是来自同一个用户,则这两个用户使用相同的密钥! 因此,每个明文的独特iv确保没有两个明文产生相同的密文。 换句话说,iv是盐 。
$plaintext = 'Testing OpenSSL Functions';
$methods = openssl_get_cipher_methods();
//$clefSecrete = 'flight';
echo '<pre>';
foreach ($methods as $method) {
$ivlen = openssl_cipher_iv_length($method);
$clefSecrete = openssl_random_pseudo_bytes($ivlen);
$iv = openssl_random_pseudo_bytes($ivlen);
$encrypted = openssl_encrypt($plaintext, $method, $clefSecrete, OPENSSL_RAW_DATA, $iv);
$decrypted = openssl_decrypt($encrypted, $method, $clefSecrete, OPENSSL_RAW_DATA, $iv);
echo 'plaintext='.$plaintext. "\n";
echo 'cipher='.$method. "\n";
echo 'encrypted to: '.$encrypted. "\n";
echo 'decrypted to: '.$decrypted. "\n\n";
}
echo '</pre>';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.