PHP

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

小樊
82
2024-09-04 23:43:10
栏目: 编程语言

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

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

  1. 加密文件:
<?php
function 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);
?>
  1. 解密文件:
<?php
function 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 个字符的密钥)。在实际应用中,你需要确保密钥的安全存储。

0
看了该问题的人还看了