我很惊讶我在网上找不到任何代码片段,建议或教程,解释了如何使用标准的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
答案 0 :(得分:0)
如何仅使用mcrypt和php标准函数来加密/解密文件?
嗯,you don't want to use mcrypt。这些天你想用钠。
您正在寻找的相关API是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;
}
同时使用两个功能:
$key = random_bytes(32);
encryptFile('input.txt', 'cipher.txt', $key);
decryptFile('cipher.txt', 'decrypt.txt', $key);