abstriction
abstriction

Reputation: 71

How to import GPG key and decrypt file using C++ GPGME

How do I simply load a gpg key to import into a context using GPGME C++ library?

I am trying to build an application that decrypts a file using GPGME but I am struggling to understand the GPU Documentation. I've tried to search the web for examples but have yet to come across one that loads in a preexisting GPG key. The attempt I made consists of trying to create a context and loading a preexisting key into which will be used to decrypt a file based on this sample code.

I keep getting "Invalid Input" as a response error and have no idea why. I have included the code with output statements removed, but commented the output returns on them.

Update: After fixing the context, the decryption outputs success althrough the file is not properly decrypted and a key does not appear to have succesfully been added. I have provided the modified code below.

#include <gpgme.h>
#include <fcntl.h>

auto main(int argc, char** argv) -> int
{
    gpgme_ctx_t ctx;
    gpgme_error_t err;
    gpgme_check_version(NULL);
    err = gpgme_new(&ctx);                          // returns Success
    gpgme_data_t keydata;

    // ATTEMPTING TO IMPORT KEY FILE
    // returns Success
    err = gpgme_data_new_from_file(&keydata, "test.gpg", 1); 

    // ATTEMPTING TO IMPORT KEY INTO CONTEXT
    err = gpgme_op_import(ctx, keydata);            // returns Success 

    // ATTEMPTING TO CHECK RESULT
    // when accessing "imported" member, returns 0 keys imported
    gpgme_import_result_t impRes = gpgme_op_import_result(ctx); 

    // DECRYPT DATA

    gpgme_data_t fileDecrypted, fileEncrypted;

    int fdEncrypt = open("EncryptedFile.tar.gz", O_RDONLY);
    int fdDecrypt = open("DecryptedFile.tar.gz", O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);

    err = gpgme_data_new_from_fd(&fileEncrypted, fdEncrypt); // returns Success
    err = gpgme_data_new_from_fd(&fileDecrypted, fdDecrypt); // returns Success 

    gpgme_decrypt_result_t dec_result;
    // returns Success
    err = gpgme_op_decrypt_start (ctx, fileEncrypted, fileDecrypted);
    dec_result = gpgme_op_decrypt_result(ctx); // returns address location

    return 0;
}

Any input is much appreciated, thanks in advance!

Upvotes: 4

Views: 3200

Answers (1)

abstriction
abstriction

Reputation: 71

The invalid value error appears to have come from the lack of setup associated with the context.

According to documentation, a new context needs to be created but for that to succeed a library version check must be called in order to initialize subsystems. Hence the additional lines of code should be added.

gpgme_check_version(NULL);
gpgme_new(&ctx);

Upvotes: 2

Related Questions