文件加密 php实现
PHP文件加密实现方法
使用PHP内置加密函数
PHP提供openssl_encrypt和openssl_decrypt函数用于文件加密解密。示例代码展示AES-256-CBC加密方式:
$method = 'AES-256-CBC';
$key = openssl_random_pseudo_bytes(32);
$iv = openssl_random_pseudo_bytes(16);
function encryptFile($inputFile, $outputFile, $key, $iv, $method) {
$data = file_get_contents($inputFile);
$encrypted = openssl_encrypt($data, $method, $key, 0, $iv);
file_put_contents($outputFile, $encrypted);
}
function decryptFile($inputFile, $outputFile, $key, $iv, $method) {
$data = file_get_contents($inputFile);
$decrypted = openssl_decrypt($data, $method, $key, 0, $iv);
file_put_contents($outputFile, $decrypted);
}
使用密码学扩展库
对于更高级需求可安装libsodium扩展:
$key = sodium_crypto_secretbox_keygen();
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
function sodiumEncrypt($inputFile, $outputFile, $key, $nonce) {
$data = file_get_contents($inputFile);
$encrypted = sodium_crypto_secretbox($data, $nonce, $key);
file_put_contents($outputFile, $nonce.$encrypted);
}
function sodiumDecrypt($inputFile, $outputFile, $key) {
$data = file_get_contents($inputFile);
$nonce = substr($data, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$ciphertext = substr($data, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$decrypted = sodium_crypto_secretbox_open($ciphertext, $nonce, $key);
file_put_contents($outputFile, $decrypted);
}
文件哈希验证
加密后建议生成文件哈希值验证完整性:
function getFileHash($filePath) {
return hash_file('sha256', $filePath);
}
$originalHash = getFileHash('original.txt');
$encryptedHash = getFileHash('encrypted.txt');
密钥安全管理
密钥应存储在安全位置,避免硬编码在脚本中:
// 推荐存储在环境变量或专用密钥管理服务
$key = getenv('ENCRYPTION_KEY');
性能优化建议
处理大文件时使用流式加密:
function streamEncrypt($source, $dest, $key, $iv, $method) {
$context = stream_context_create();
$sourceStream = fopen($source, 'r', false, $context);
$destStream = fopen($dest, 'w', false, $context);
while (!feof($sourceStream)) {
$chunk = fread($sourceStream, 8192);
$encrypted = openssl_encrypt($chunk, $method, $key, OPENSSL_RAW_DATA, $iv);
fwrite($destStream, $encrypted);
}
fclose($sourceStream);
fclose($destStream);
}






