我使用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;
}
答案 0 :(得分:2)
我有完全相同的问题,然后我用Google搜索了我的问题并最终在这里,就我问过的同一个问题。所以我不得不去其他地方搜索。
我发现this article有助于解释官方php文档的缺点。另一篇内容相似的文章是here。
最后它归结为密钥/密码。 openssl_encrypt库所期望的是密钥而不是密码。密钥的大小必须是密码的内部密钥大小。第一篇文章说,如果你提供一个更长的密钥,那么多余的密钥就被丢弃,一个比预期更短的密钥用零填充,即\ x00字节。我没有测试过这个事实。
我已将您的代码编辑为如下所示。
我使用过的想法是,密码所期望的初始向量的大小也是它所期望的密钥的大小。所以在这里,我正在传递密钥而不是密码。只需找到将密码转换为密钥的方法。
在您的代码中,您没有传递选项和iv(初始化向量)。
iv是一个字符串密码&#39;混合&#39;用加密前的明文。那么密码加密的是这个&#39;混合物&#39;。这很重要吗?是!如果没有这种“混合”,一对相同的明文会产生一对相同的密文,这会导致攻击;如果两个相同的明文 - 密文对不是来自同一个用户,则这两个用户使用相同的密钥!因此,每个明文的独特iv确保没有两个明文产生相同的密文。换句话说,iv是salt。
$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>';