【问题标题】:phpseclib - set IV modify images data URIphpseclib - 设置 IV 修改图像数据 URI
【发布时间】:2021-02-27 03:30:59
【问题描述】:

我正在使用 phpseclib 加密/解密某些图像的数据 uri。我注意到,当我使用 IV 时,data:image/png;base64,data:image/jpg;base64,data:image/jpeg;base64 部分传递的数据 uri 将丢失,只有 base64 字符串的其余部分会保留,我将无法显示解密操作后的图像。是否可以在不丢失每个数据 uri 加密的那部分的情况下使用 IV?

//data URI creation from uploaded image using PHP-dataURI https://github.com/alchemy-fr/PHP-dataURI
$dataObject = DataURI\Data::buildFromFile('myimage.jpg');
//data URI encrypt
$cipher = new AES();
//set password for encryption
$cipher->setPassword($password);
//set the IV - this will corrupt data uri generated
$cipher->setIV(Random::string($cipher->getBlockLength() >> 3));
//encrypting the data
$output = $cipher->encrypt(DataURI\Dumper::dump($dataObject));

【问题讨论】:

  • @ArtjomB。您建议的问题的实现适用于 c# 和 java。我正在使用 PHP,所以我找不到任何可以帮助我解决问题的有用信息。无论如何,谢谢。
  • 你是说你的解密返回了损坏的明文。让我为您改写链接的答案。 IV 在解密期间需要与该单个密文的加密相同。如果您创建一个随机 IV 而不保存它,那么您将无法在解密期间恢复明文的前 16 个字节。 IV 不是秘密的,但可以与密文一起发送。我们通常将其添加到密文中。这有帮助吗?
  • 好的,但是我正在使用库函数来附加 IV $cipher->setIV(Random::string($cipher->getBlockLength() >> 3)); 我不确定我是否可以做同样的事情并在解密时获得相同的结果,我已经按照建议完成了从文档
  • 不要忘记包含完整的代码,包括解密部分。

标签: php encryption phpseclib data-uri


【解决方案1】:

这是我用来解决此问题的方法。我是 phplibsec 的新手,所以我以错误的方式使用 $cipher->setIV(Random::string($cipher->getBlockLength() >> 3)) 方法来设置和读取 IV。 phpseclib 文档不是很有用,并且缺乏关于如何正确实现加密和解密方法的示例,特别是没有提供如何管理 IV 的示例。经过对 SO 的一些研究并感谢社区的帮助,我已经弄清楚了如何管理 IV。

数据uri的加密:

//data URI creation from uploaded image using PHP-dataURI https://github.com/alchemy-fr/PHP-dataURI
$dataObject = DataURI\Data::buildFromFile('myimage.jpg');
//data URI encrypt
$cipher = new AES();
//set password for encryption
$cipher->setPassword($password);
//random IV creation
$iv = Random::string($cipher->getBlockSize() >> 3);
//set the IV
$cipher->setIV($iv);
//encrypting the data
$encrypted = $cipher->encrypt(DataURI\Dumper::dump($dataObject));
//output
$output = $iv.$encrypted;

在加密脚本中,我将随机生成的 IV 分配给了一个变量,该变量在加密后附加到加密数据中。这是因为需要 IV 才能正确解密数据,这意味着它需要存储在数据库中或附加/附加到数据中(不,这样做没有安全风险)。然后可以使用substr() 函数以这种方式从加密数据中提取附加的IV:

//data URI decrypt
$cipher = new AES();
//set previously selected password for encryption
$cipher->setPassword($password);
//extract the IV from encrypted data
$ivLength = $cipher->getBlockLength() >> 3;
$iv = substr($encrypted, 0, $ivLength);
//set the IV
$cipher->setIV($iv);
//removing the IV from the data before decrypt
$data = substr($encrypted, $ivLength);
//decrypting the data
$output = $cipher->decrypt($data);

解密后原始base64数据uri将按预期返回。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-17
    • 2018-03-11
    • 2017-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多