Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Encrypt/Decrypt file in QT. How?



  • Hello all!
    Is there in-box solution in QT for encrypting/decrypting file in Qt? If no what is better to use in QT? I am trying to avoid to use plain C and OpenSSL directly. Is there any library or framework for this issue?


  • Lifetime Qt Champion

    Hi,

    QCA from the KDE project.



  • Hi,
    I use this and liked...

    https://wiki.qt.io/Simple_encryption_with_SimpleCrypt

    Regards,
    Mucip:)



  • Hi,
    openssl is pretty easy to use :

    uchar const KEY_CRYPT[] = "-UKfdjdskf--**fsnx"; // What you want ...
    uchar const KEY_IV[] = "Compl3xES3quence"; // What you want ...
    
    #include <openssl/aes.h>
    #include <openssl/evp.h>
    #include <QFile>
    
    bool decryptOrEncrypt(bool encrypt)
    {
        QFile srcFile;
        QFile destFile;
    
        if(encrypt)
        {
            srcFile.setFileName(m_destinationFile);
            destFile.setFileName(m_encryptedFile);
        }
        else
        {
            srcFile.setFileName(m_encryptedFile);
            destFile.setFileName(m_destinationFile);
        }
    
        if(!srcFile.open(QIODevice::ReadOnly))
        {
            return false;
        }
    
        if(!destFile.open(QIODevice::WriteOnly))
        {
            return false;
        }
    
        const int MAX_BUFFER_SIZE = 1024;
        int out_len;
        EVP_CIPHER_CTX * ctx = EVP_CIPHER_CTX_new();
    
        EVP_CipherInit(ctx, EVP_aes_128_cbc(), KEY_CRYPT, KEY_IV , encrypt);
        int blocksize = EVP_CIPHER_CTX_block_size(ctx);
        QByteArray cipher_buf;
        cipher_buf.resize(MAX_BUFFER_SIZE + blocksize);
    
        qint64 size = 0;
    
        while(!srcFile.atEnd())
        {
            // Read in data in blocks until EOF. Update the ciphering with each read.
            QByteArray inRead = srcFile.read(MAX_BUFFER_SIZE);
            EVP_CipherUpdate(ctx, reinterpret_cast<uchar *>(cipher_buf.data()), &out_len, reinterpret_cast<uchar *>(inRead.data()), inRead.count());
            destFile.write(cipher_buf.data(), out_len);
            size += out_len;
        }
    
        // Now cipher the final block and write it out.
        EVP_CipherFinal(ctx, reinterpret_cast<uchar *>(cipher_buf.data()), &out_len);
        destFile.write(cipher_buf.data(), out_len);
        size += out_len;
        destFile.close();
        srcFile.close();
    
        EVP_CIPHER_CTX_free(ctx);
    
        return true;
    }
    

  • Lifetime Qt Champion

    Hi
    It should be a really strong coffee before that would look even remotely easy to me..:)
    But thank you for the sample.

     EVP_CipherUpdate(ctx, reinterpret_cast<uchar *>(cipher_buf.data()), &out_len, reinterpret_cast<uchar *>(inRead.data()), inRead.count());
    


  • Solution found https://github.com/bricke/Qt-AES Issue closed.


Log in to reply