如何在 php 中加密解密 .pdf、.docx 文件?

Aak*_*ani 3 php pdf encryption doc docx

我正在尝试用 PHP 加密/解密文件。到目前为止,我对 .txt 文件是成功的,但当涉及 .pdf 和 .doc 或 .docx 时,我的代码失败了,即它给出了荒谬的结果。谁能建议我的代码中的修改/替代方案?提前致谢!

这是加密函数

function encryptData($value)
{
   $key = "Mary has one cat";
   $text = $value;
   $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
   $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
   $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $text, MCRYPT_MODE_ECB, $iv);
   return $crypttext;
}
Run Code Online (Sandbox Code Playgroud)

这是解密函数

function decryptData($value)
{
   $key = "Mary has one cat";
   $crypttext = $value;
   $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
   $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
   $decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $crypttext, MCRYPT_MODE_ECB, $iv);
   return trim($decrypttext);
} 
Run Code Online (Sandbox Code Playgroud)

Lib*_*bby 6

我使用此博客来帮助我在本地计算机上加密/解密 pdf 文件,openssl_encrypt因为mcrypt它在 php7 中已弃用。

首先,获取pdf的文件内容:

$msg = file_get_contents('example.pdf');
Run Code Online (Sandbox Code Playgroud)

然后我调用了博文中写的加密函数:

$msg_encrypted = my_encrypt($msg, $key);
Run Code Online (Sandbox Code Playgroud)

然后我打开要写入的文件并写入新的加密消息:

$file = fopen('example.pdf', 'wb');
fwrite($file, $msg_encrypted);
fclose($file);
Run Code Online (Sandbox Code Playgroud)

作为参考,以防博客宕机,以下是博客的加密和解密函数:

$key = 'bRuD5WYw5wd0rdHR9yLlM6wt2vteuiniQBqE70nAuhU=';

function my_encrypt($data, $key) {
    // Remove the base64 encoding from our key
    $encryption_key = base64_decode($key);
    // Generate an initialization vector
    $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
    // Encrypt the data using AES 256 encryption in CBC mode using our encryption key and initialization vector.
    $encrypted = openssl_encrypt($data, 'aes-256-cbc', $encryption_key, 0, $iv);
    // The $iv is just as important as the key for decrypting, so save it with our encrypted data using a unique separator (::)
    return base64_encode($encrypted . '::' . $iv);
}



function my_decrypt($data, $key) {
    // Remove the base64 encoding from our key
    $encryption_key = base64_decode($key);
    // To decrypt, split the encrypted data from our IV - our unique separator used was "::"
    list($encrypted_data, $iv) = explode('::', base64_decode($data), 2);
    return openssl_decrypt($encrypted_data, 'aes-256-cbc', $encryption_key, 0, $iv);
}
Run Code Online (Sandbox Code Playgroud)