我在网上发现了一些有用的教程,但我不确定是否有最好的选择。我想用高度安全的算法加密文件(我有点偏执)但同时我在寻找速度(我知道它有点矛盾)......所以我选择了AES-256 ..但是使用AES-256和PHP加密文件的最佳方法是什么?
答案 0 :(得分:6)
对于对称算法,请使用Mcrypt。
请注意,从安全角度来看,使用该库可能会有风险,而不知道所有内容的作用。看看一些ready-made solutions。
(顺便提一下,支持的密码是here)。
Mcrypt扩展在7.1中已弃用,在7.2中已删除,因此您需要一个替代方案。请改用Sodium。
答案 1 :(得分:-1)
使用AES-256的PHP Mcrypt基于文件的对称加密(将IV存储为文件的前16个字节),并使用sha256 hmac进行身份验证加密:
<?php
print_r(mcrypt_list_algorithms());//check if rijndael-128 available
print_r(stream_get_filters()); //should contain mcrypt.* and mdecrypt.*
//16 byte key=>AES-128, 24 byte key=>AES-192, 32 byte key=>AES-256
$key='BkK8Jts................sPo38nNcW';
//encrypt file
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_DEV_RANDOM);//or MCRYPT_DEV_URANDOM
$fin = fopen($in_filename, "rb");
$fcrypt = fopen($aes_filename, 'wb');
fwrite($fcrypt, $iv);
$opts = array('iv'=>$iv, 'key'=>$key, 'mode'=>'cbc');
stream_filter_append($fcrypt, 'mcrypt.rijndael-128', STREAM_FILTER_WRITE, $opts);
while (!feof($fin))
{
fwrite($fcrypt, fread($fin, 8192));
}
fclose($fcrypt);
fclose($fin);
$hmac_real = hash_hmac_file('sha256', $aes_filename, $key, $raw=false);
//decrypt file
$hmac_calc = hash_hmac_file('sha256', $aes_filename, $key, $raw=false);
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$fcrypt = fopen($aes_filename, "rb");
$fout = fopen($out_filename, 'wb');
$iv = fread($fcrypt, $iv_size);
$opts = array('iv'=>$iv, 'key'=>$key, 'mode'=>'cbc');
stream_filter_append($fcrypt, 'mdecrypt.rijndael-128', STREAM_FILTER_READ, $opts);
while (!feof($fcrypt))
{
$block = fread($fcrypt, 8192);
$block = feof($fcrypt)? rtrim($block,"\0") : $block;//removes aes pad
fwrite($fout, $block);
}
fclose($fout);
fclose($fcrypt);
$hmac_calc==$hmac_real or unlink($out_filename);//invalid if they don't match
请参阅:http://php.net/manual/en/filters.encryption.php
AES-256有一个已知的弱点,因此您可以使用16字节密钥在此代码中触发AES-128 见:https://www.schneier.com/blog/archives/2009/07/another_new_aes.html