使用 php/mcrypt 加密文件会损坏 docx(和其他Microsoft Office 2007)文件,但其他文件


Encrypting files with php/mcrypt is corrupting docx (and other Microsoft Office 2007) files but others are fine

我正在使用CodeIgniter应用程序来加密上传的文件,然后在下载时解密它们,以便它们可以安全地存储(以及其他安全措施)。除了docx(和其他Microsoft Office 2007+)文件外,这一切都可以正常工作。下载这些内容后,它们已成功解密,但 Office 会将其检测为损坏。这些可以修复,因此它们没有完全损坏,但是文件中的某些内容与原始版本相比发生了变化,这使得Office将其视为损坏。正如我所提到的,这似乎不会发生在任何其他文件类型上(我已经注意到)。docx 文件的大小也略有不同(只有字节的问题),而其他类型的文件则不同。

为了加密,我上传文件,使用 file_get_contents() 将内容读入字符串中,然后通过加密库中的 CodeIgniter 的 encode() 运行字符串,然后将文件保存回磁盘,删除原始文件:

function mcrypt_encode($data, $key)
{
    $init_size = mcrypt_get_iv_size($this->_get_cipher(), $this->_get_mode());
    $init_vect = mcrypt_create_iv($init_size, MCRYPT_RAND);
    return $this->_add_cipher_noise($init_vect.mcrypt_encrypt($this->_get_cipher(), $key, $data, $this->_get_mode(), $init_vect), $key);
}

并解码:

function mcrypt_decode($data, $key)
{
    $data = $this->_remove_cipher_noise($data, $key);
    $init_size = mcrypt_get_iv_size($this->_get_cipher(), $this->_get_mode());
    if ($init_size > strlen($data))
    {
        return FALSE;
    }
    $init_vect = substr($data, 0, $init_size);
    $data = substr($data, $init_size);
    return rtrim(mcrypt_decrypt($this->_get_cipher(), $key, $data, $this->_get_mode(), $init_vect), "'0");
}

然后通过 CodeIgniter 的 force_download() 运行解码的字符串

默认密码为MCRYPT_RIJNDAEL_256,模式为MCRYPT_MODE_CBC。我的服务器上启用了 Mcrypt 和MCRYPT_RIJNDAEL_256。

如果有人能指出我正确的方向,为什么会发生这种情况,我们将不胜感激。

非常感谢

这是file_get_contents和二进制数据的已知错误。 http://bugs.php.net/bug.php?id=42661

base64_encode()文件的file_get_contents(),然后加密。

下载前base64_decode()加密文件的解密file_get_contents()

我做了几乎同样的事情,从谷歌来到这里。

我现在解决了。问题不在于file_get_contents(),问题在于编码点火器中的编码功能。该函数删除某些特殊字符,从而从文件中删除数据。有趣的是Microsoft办公室如何能够修复它。