php - phpseclib - 设置 IV 修改图像数据 URI
问题描述
我正在使用 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));
解决方案
这是我用来解决这个问题的方法。我是 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 将按预期返回。
推荐阅读
- python - 列表拒绝追加
- javascript - Firebase Firestorage 上传过程从 0 跳转到 100
- vue.js - VueJS 和 antdesign vue - 错误:找不到模块 'babel-plugin-import' from
- php - phpspreadsheet:如何在单元格和图像之间添加一些边距?
- python - 如何使用 winsock2 库在 C 中发送程序当前工作目录?
- azure - Azure CDN 通常是否应该用于提供图像(静态布局元素除外)?
- javascript - 为使用相同处理程序动态创建的每个组件创建单独的状态
- c++ - 为什么我们不能将 char 指针静态转换为 int 指针?
- python - 出现错误:在 python 3.7 的“test1”中找不到“__main__”模块
- python - 在本地 XAMPP 服务器上显示的 Python 脚本