首页 > 解决方案 > phpseclib - 设置 IV 修改图像数据 URI

问题描述

我正在使用 phpseclib 加密/解密某些图像的数据 uri。我注意到,当我使用 IV 时data:image/png;base64data: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));

标签: phpencryptionphpseclibdata-uri

解决方案


这是我用来解决这个问题的方法。我是 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 将按预期返回。


推荐阅读