如何在PHP中加密-decrypt .pdf,.docx文件?

时间:2015-01-26 17:13:34

标签: php pdf encryption docx doc

我正在尝试用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;
}

这是解密功能

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);
} 

1 个答案:

答案 0 :(得分:1)

我使用this blog帮助我使用openssl_encrypt加密/解密本地计算机上的pdf文件,因为在php7中不推荐使用mcrypt

首先,您将获得pdf的文件内容:

$msg = file_get_contents('example.pdf');

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

$msg_encrypted = my_encrypt($msg, $key);

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

$file = fopen('example.pdf', 'wb');
fwrite($file, $msg_encrypted);
fclose($file);

作为参考,如果博客发生故障,以下是博客中的加密和解密功能:

$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);
}