【发布时间】: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。