【问题标题】:encrypt decrypt a file: SVG or XML with PHP加密解密文件:使用 PHP 的 SVG 或 XML
【发布时间】:2018-07-15 15:08:20
【问题描述】:

我使用这两个函数来加密/解密文件:

    private function encrypt_file($source,$destination,$passphrase,$stream=NULL) {
    // $source can be a local file...
    if($stream) {
        $contents = $source;
        // OR $source can be a stream if the third argument ($stream flag) exists.
    }else{
        $handle = fopen($source, "rb");
        $contents = @fread($handle, filesize($source));
        fclose($handle);
    }

    $iv = substr(md5("\x1B\x3C\x58".$passphrase, true), 0, 8);
    $key = substr(md5("\x2D\xFC\xD8".$passphrase, true) . md5("\x2D\xFC\xD9".$passphrase, true), 0, 24);
    $opts = array('iv'=>$iv, 'key'=>$key);
    $fp = fopen($destination, 'wb') or die("Could not open file for writing.");
    stream_filter_append($fp, 'mcrypt.tripledes', STREAM_FILTER_WRITE, $opts);
    fwrite($fp, $contents) or die("Could not write to file.");
    fclose($fp);

}


private function decrypt_file($file,$passphrase) {

    $iv = substr(md5("\x1B\x3C\x58".$passphrase, true), 0, 8);
    $key = substr(md5("\x2D\xFC\xD8".$passphrase, true) .
            md5("\x2D\xFC\xD9".$passphrase, true), 0, 24);
    $opts = array('iv'=>$iv, 'key'=>$key);
    $fp = fopen($file, 'rb');
    stream_filter_append($fp, 'mdecrypt.tripledes', STREAM_FILTER_READ, $opts);

    return $fp;
}

它适用于大多数文件。但是一般来说 SVG 或 XML 文件存在问题。例如,对 SVG 文件的解密会在最后一行给出字符“NUL NUL ...”。如图所示:

【问题讨论】:

  • 你用什么来读写文件(以及什么标志)?
  • 我很抱歉。我没有给出正确的功能。我必须修改我的问题,但我无法编辑它。
  • 加密过滤器在新的 PHP 版本中被弃用:secure.php.net/manual/de/filters.encryption.php
  • 来自example 1, $data = rtrim(stream_get_contents($fp));//trims off null padding
  • 谢谢@James,这就是问题所在。现在可以了

标签: php xml svg encryption


【解决方案1】:

您可能直接从PHP documentation 复制了代码。但是:正如它在同一页上所说,这段代码有几个问题。基本上使用md5 进行密钥派生远非最佳。有关完整说明,请参阅http://www.cryptofails.com/post/70059608390/php-documentation-woes。不推荐使用此和加密过滤器(请参阅相同的链接),我建议放弃这种加密方式。

我还建议使用一些经过测试的 PHP 加密库,例如 libsodium-php 这也将集成到 php7 本身中。 (Source)

返回主题:您看到的是加密填充。为了使分组密码(在您的情况下为 DES)起作用,每个块必须具有算法给定的大小。由于大多数数据不关心块大小,因此算法必须应用某种填充。

解密时,您还会收到填充值。要获得您的输出值,您需要在之后删除填充。在您的情况下,这将是修剪尾随 NUL 字符。它已经在文档中(感谢@James 指出这一点)

$data = rtrim(stream_get_contents($fp)); //trims off null padding

【讨论】:

    猜你喜欢
    • 2014-01-22
    • 2021-08-22
    • 2010-12-26
    • 2018-09-23
    • 2016-02-14
    • 2012-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多