使用Qt Cryptographic Architecture加密数据

时间:2012-11-13 23:57:19

标签: c++ qt encryption aes

如何使用带有AES-256加密的Qt加密体系结构使用密码加密数据?

我尝试了代码: 但是当我运行该程序时,它失败了。

void encryptSomeData()
{
    QCA::Initializer init = QCA::Initializer();
    QCA::SymmetricKey key = QCA::SymmetricKey(16);
    QCA::InitializationVector iv = QCA::InitializationVector(16);
    //the program broke here.
    QCA::Cipher cipher = QCA::Cipher(QString("aes128"), QCA::Cipher::CBC,
                                     QCA::Cipher::DefaultPadding, QCA::Encode,
                                     key, iv);
    if (!QCA::isSupported("aes128-cbc-pkcs7"))
    {
        qDebug() << "AES128 CBC PKCS7 not supported - "
                    "please check if qca-ossl plugin"
                    "installed correctly !";
        return;
    }
    QString s = "Hello, world !";
    QCA::SecureArray secureData = s.toAscii();
    QCA::SecureArray encryptedData = cipher.process(secureData);
    if (!cipher.ok())
    {
        qDebug() << "Encryption failed !";
        return;
    }
    qDebug() << QString(qPrintable(QCA::arrayToHex(encryptedData.toByteArray())));
    cipher.setup(QCA::Decode, key, iv);
    QCA::SecureArray decryptedData = cipher.process(encryptedData);
    if (!cipher.ok())
    {
        qDebug() << "Decryption failed !";
        return;
    }
    qDebug() << QString(decryptedData.data());
}

1 个答案:

答案 0 :(得分:0)

在C ++中进行加密时,我使用open ssl库。设置非常简单,完成后您可以使用以下代码作为起点

class myaes
{
private:
    EVP_CIPHER_CTX en;
public:
    myaes(unsigned char *key_data, int key_data_len, unsigned char *salt);
    QByteArray encrypt(QString plaintext,int len);
};

myaes::myaes(unsigned char * key_data,int key_data_len,unsigned char * salt)
{
    int x, nrounds = 5;
    unsigned char iv[16];
    memset(&iv[0],0,16);


    x = EVP_BytesToKey(EVP_aes_128_cbc(), EVP_sha1(), salt, key_data, key_data_len, nrounds, key, iv);*/
    EVP_CIPHER_CTX_init(&en);
    EVP_EncryptInit_ex(&en, EVP_aes_128_cbc(), NULL,(const unsigned char*) &key[0], iv);

}

QByteArray myaes::encrypt(QString plaintext, int len)
{
     int c_len = len + 128, f_len = 0;
     unsigned char *ciphertext = new unsigned char[c_len];
     qDebug() << plaintext;
     EVP_EncryptInit(&en,NULL,NULL,NULL);
     EVP_EncryptUpdate(&en, ciphertext, &c_len, (unsigned char*)plaintext.toStdString().data(), len);
     EVP_EncryptFinal_ex(&en, ciphertext+c_len, &f_len);
     len = c_len + f_len;
     QByteArray tmp;
     tmp.insert(0,(const char*)ciphertext,len);
     qDebug() << QString(tmp);
     return tmp;
}