我在研究Internet上的AES加密时发现了以下代码。在此代码中,我发现key
和iv
使用hash function
生成,并使用sha256
。我想知道这种方法是否对使用PHP加密文本是安全的。用于AES加密的生成密钥的安全
,我在网上找到了下面给出的代码,
<?php
function encrypt_decrypt($action, $string) {
$output = false;
$encrypt_method = "AES-256-CBC";
$secret_key = 'This is my secret key';
$secret_iv = 'This is my secret iv';
// hash
$key = hash('sha256', $secret_key);
// iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
$iv = substr(hash('sha256', $secret_iv), 0, 16);
if ($action == 'encrypt') {
$output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
$output = base64_encode($output);
} else if($action == 'decrypt') {
$output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
}
return $output;
}
$plain_txt = "This is my plain text";
echo "Plain Text =" .$plain_txt. "\n";
$encrypted_txt = encrypt_decrypt('encrypt', $plain_txt);
echo "Encrypted Text = " .$encrypted_txt. "\n";
$decrypted_txt = encrypt_decrypt('decrypt', $encrypted_txt);
echo "Decrypted Text =" .$decrypted_txt. "\n";
if ($plain_txt === $decrypted_txt) echo "SUCCESS";
else echo "FAILED";
echo "\n";
?>
我对代码做了一些更改。你能看看代码并告诉我这是否会有所作为?这里是代码的链接https://codeshare.io/5wydZB –
第1号。使用CPRNG,而不是使用'array_rand'的自制实现,它声明:“它使用伪随机数生成器**不适用于加密目的。“ 2.从文档'crypt'不会迭代,并且需要足够的迭代来需要100ms。这个IV似乎没有通过解密。 4.海事组织你最好的选择是使用[RNCryptor](https://github.com/RNCryptor/RNCryptor-php),它使事情正确,增加认证,版本控制并且经过审查。 – zaph