如何结合fopen实现PHP文件的加密解密

   2024-09-30 2680
核心提示:要在 PHP 中使用 fopen 函数实现文件的加密和解密,你可以使用对称加密算法,例如 AES首先,确保已安装了 OpenSSL 扩展。大多数

要在 PHP 中使用 fopen 函数实现文件的加密和解密,你可以使用对称加密算法,例如 AES

首先,确保已安装了 OpenSSL 扩展。大多数环境中默认已经安装。

加密文件:
<?phpfunction encryptFile($inputFilename, $outputFilename, $key) {    $cipher = "AES-256-CBC";    $ivlen = openssl_cipher_iv_length($cipher);    $iv = openssl_random_pseudo_bytes($ivlen);    $inputFile = fopen($inputFilename, 'rb');    $outputFile = fopen($outputFilename, 'wb');    // 将初始化向量写入加密文件    fwrite($outputFile, $iv);    while (!feof($inputFile)) {        $plaintext = fread($inputFile, 16 * 1024);        $ciphertext = openssl_encrypt($plaintext, $cipher, $key, OPENSSL_RAW_DATA, $iv);        fwrite($outputFile, $ciphertext);    }    fclose($inputFile);    fclose($outputFile);}$inputFilename = 'plaintext.txt';$outputFilename = 'encrypted.txt';$key = 'your-32-character-key';encryptFile($inputFilename, $outputFilename, $key);?>
解密文件:
<?phpfunction decryptFile($inputFilename, $outputFilename, $key) {    $cipher = "AES-256-CBC";    $ivlen = openssl_cipher_iv_length($cipher);    $inputFile = fopen($inputFilename, 'rb');    $outputFile = fopen($outputFilename, 'wb');    // 读取加密文件中的初始化向量    $iv = fread($inputFile, $ivlen);    while (!feof($inputFile)) {        $ciphertext = fread($inputFile, 16 * 1024);        $plaintext = openssl_decrypt($ciphertext, $cipher, $key, OPENSSL_RAW_DATA, $iv);        fwrite($outputFile, $plaintext);    }    fclose($inputFile);    fclose($outputFile);}$inputFilename = 'encrypted.txt';$outputFilename = 'decrypted.txt';$key = 'your-32-character-key';decryptFile($inputFilename, $outputFilename, $key);?>

这两个示例中的 encryptFiledecryptFile 函数分别用于加密和解密文件。请注意,密钥应该是随机生成的,并且足够长(在这个例子中,我们使用了一个 32 个字符的密钥)。在实际应用中,你需要确保密钥的安全存储。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号