QT:AES-256-CBC 根据 PHP 代码在 C++ 中加密/解密
Posted
技术标签:
【中文标题】QT:AES-256-CBC 根据 PHP 代码在 C++ 中加密/解密【英文标题】:QT: AES-256-CBC Encrypt/Decript in C++ according to PHP Code 【发布时间】:2019-09-30 08:35:01 【问题描述】:我有一个用于加密/解密 AES-256-CBC 的简单 php 代码:
function safeEncrypt($token)
$enc_iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length("aes-256-cbc"));
return openssl_encrypt($token, "aes-256-cbc", "passToCrypt", 0, $enc_iv) . "::" . bin2hex($enc_iv);
function safeDecrypt($token)
$enc_iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length("aes-256-cbc"));
list($token, $enc_iv) = explode("::", $token);
return openssl_decrypt($token, "aes-256-cbc", "passToCrypt", 0, hex2bin($enc_iv));
我正在为 QML 应用程序中的 c++ 寻找相同的方式。 到目前为止我有这个(我不知道如何处理IV)
cryption.h:
#ifndef CRYPTION_H
#define CRYPTION_H
#include <QObject>
#include <QCryptographicHash>
class Cryption : public QObject
Q_OBJECT
public:
explicit Cryption(QObject *parent = nullptr);
Q_INVOKABLE QString encrypt(QString strToEncrypt);
Q_INVOKABLE QString decrypt(QString strToDecrypt);
private:
QString method;
QString key;
QAESEncryption encryption(QAESEncryption::AES_256, QAESEncryption::CBC);
signals:
public slots:
;
#endif // CRYPTION_H
cryption.cpp:
#include "cryption.h"
#include <QCryptographicHash>
Cryption::Cryption(QObject *parent) :
QObject(parent)
// Main Settings
method = "aes-256-cbc";
key = "passToCrypt";
QString Cryption::encrypt(QString strToEncrypt)
QByteArray hashKey = QCryptographicHash::hash(key.toLocal8Bit(), QCryptographicHash::Sha256);
// QByteArray hashIV = QCryptographicHash::hash(iv.toLocal8Bit(), QCryptographicHash::Md5);
QByteArray encodeText = encryption.encode(strToEncrypt.toLocal8Bit(), hashKey, hashIV);
return encodeText;
QString Cryption::decrypt(QString strToEncrypt)
QByteArray hashKey = QCryptographicHash::hash(key.toLocal8Bit(), QCryptographicHash::Sha256);
// QByteArray hashIV = QCryptographicHash::hash(iv.toLocal8Bit(), QCryptographicHash::Md5);
QByteArray decodeText = encryption.decode(encodeText, hashKey, hashIV);
QString decodedString = QString(encryption.removePadding(decodeText));
return decodedString;
你能帮我完成吗? 主要是我不知道如何像 PHP 那样处理 IV(一些随机数,hex2bin)并且 IV 被保存到编码字符串(ENCODED_STRING::USED_IV)中,因此 IV 可以稍后用于解码
【问题讨论】:
OT:有趣的是在 Qt MD5 中如何被称为 _cryptographic hash。 【参考方案1】:在您的 PHP 代码中,initialization vector (IV) 是使用随机数生成器生成的。你可以对 Qt 做同样的事情。例如:
QByteArray iv = QByteArray(16, 0);
for(int i=0; i<16; ++i)
iv[i] = static_cast<char>(QRandomGenerator::system()->bounded(255));
相反,您关注的example 会创建一个包含任意文本的字符串,然后计算它的 MD5 哈希值。使用上面的方法更直接,但是你可以在计算hash之前做同样的事情或者generate a random string。
【讨论】:
以上是关于QT:AES-256-CBC 根据 PHP 代码在 C++ 中加密/解密的主要内容,如果未能解决你的问题,请参考以下文章
前端加密-aes-256-cbc(服务端是php,项目是用的vue)
php openssl aes-256-cbc key长度自动匹配了128的长度,为啥
无法使用来自 AES-256-CBC 的 pgcrypto 解密,但 AES-128-CBC 可以