[英]How to encrypt/decrypt files with php (mcrypt)?
我很惊讶我没有在网上找到任何代码片段、建议或教程来解释如何仅使用标准 php 组件加密文件。
所以我问你的建议:如何仅使用 mcrypt 和 php 标准函数来加密/解密文件? 我没有使用 gnupg 的选项。 不,实际上,我的问题是:如何在不弄乱我的文件的情况下执行上述操作? 因为我已经在对这些文件进行加密/解密(使用 mcrypt/AES),而且它适用于 jpeg、PDF、some.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 标准函数加密/解密文件?
好吧, 你不想使用 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.