如何仅使用mcrypt和php标准函数来加密/解密文件?
使用钠(PHP 7.2 +,PECL ext / sodium或sodium_compat)加密文件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;
}