令我惊讶的是,我没有在网络上找到任何说明如何仅使用标准php组件加密文件的代码段,建议或教程。
因此,我向您提出建议:如何仅使用mcrypt和php标准函数来加密/解密文件?我没有选择使用gnupg。不,实际上,我的问题是:如何在不弄乱我的文件的情况下完成上述操作?因为我已经使用mcrypt / AES对这些文件进行了加密/解密,所以它对于jpegs,PDF,一些.doc文件以及受密码保护的.docx文件非常有效。它不适用于非安全的.docx文件和许多其他文件类型。
我当前的代码是这个。基本上,我真的只是打开文件,用mcrypt / AES搅动数据,然后将其写入服务器/让用户下载。
上传后编码:
// using codeigniter's encryption library, which uses mcrypt and the AES cypher
$this->load->library('encrypt');
$pathandname = $config['upload_path'].$output['content'][$a]['file_name'];
$theFile = file_get_contents($pathandname);
$fh = fopen($pathandname,'w');
fwrite($fh,$this->encrypt->encode($theFile));
fclose($fh);
解码并下载:
$this->load->library('encrypt');
$pathandname = $filelocation.$results[0]['encryptedfile'];
$theFile = file_get_contents($pathandname);
$decrypted = $this->encrypt->decode($theFile);
force_download($filename, $decrypted); // a codeigniter function to force download via headers
如何仅使用mcrypt和php标准函数来加密/解密文件?
嗯,you don't want to use mcrypt。这些天你想用钠。
您正在寻找的相关API是crypto_secretstream
。
crypto_secretstream
解密看起来像这样:
const CUSTOM_CHUNK_SIZE = 8192;
/**
* @ref https://stackoverflow.com/q/11716047
*/
function encryptFile(string $inputFilename, string $outputFilename, string $key): bool
{
$iFP = fopen($inputFilename, 'rb');
$oFP = fopen($outputFilename, 'wb');
[$state, $header] = sodium_crypto_secretstream_xchacha20poly1305_init_push($key);
fwrite($oFP, $header, 24); // Write the header first:
$size = fstat($iFP)['size'];
for ($pos = 0; $pos < $size; $pos += CUSTOM_CHUNK_SIZE) {
$chunk = fread($iFP, CUSTOM_CHUNK_SIZE);
$encrypted = sodium_crypto_secretstream_xchacha20poly1305_push($state, $chunk);
fwrite($oFP, $encrypted, CUSTOM_CHUNK_SIZE + 17);
sodium_memzero($chunk);
}
fclose($iFP);
fclose($oFP);
return true;
}
同时使用两个功能:
/**
* @ref https://stackoverflow.com/q/11716047
*/
function decryptFile(string $inputFilename, string $outputFilename, string $key): bool
{
$iFP = fopen($inputFilename, 'rb');
$oFP = fopen($outputFilename, 'wb');
$header = fread($iFP, 24);
$state = sodium_crypto_secretstream_xchacha20poly1305_init_pull($header, $key);
$size = fstat($iFP)['size'];
$readChunkSize = CUSTOM_CHUNK_SIZE + 17;
for ($pos = 24; $pos < $size; $pos += $readChunkSize) {
$chunk = fread($iFP, $readChunkSize);
[$plain, $tag] = sodium_crypto_secretstream_xchacha20poly1305_pull($state, $chunk);
fwrite($oFP, $plain, CUSTOM_CHUNK_SIZE);
sodium_memzero($plain);
}
fclose($iFP);
fclose($oFP);
return true;
}