ragebiswas
ragebiswas

Reputation: 3878

OpenSSL EVP_aes_128_gcm with BIO API

I'm trying to use OpenSSL's BIO interfaces with the AES GCM 128 bit encryption mode. I'm almost directly copying an example from a book (Network Security with OpenSSL example 4.8) and just changing the encryption mode to aes_128_gcm, but things don't work (an empty file is written). Since I'm new to OpenSSL I'm probably doing something silly. Can you please tell me what's wrong in the snippet below:

int main()
{
    OpenSSL_add_all_algorithms();
    char *msg = "hello";
    return write_data("hello.out", msg, strlen(msg),  "1234567890123456");
}

int write_data(const char *filename, char *out, int len, unsigned char *key)
{
    int total, written;
    BIO *cipher, *b64, *buffer, *file;
    file = BIO_new_file(filename, "w");
    buffer = BIO_new(BIO_f_buffer());
    b64 = BIO_new(BIO_f_base64());
    cipher = BIO_new(BIO_f_cipher());
    BIO_set_cipher(cipher, EVP_aes_128_gcm(), key, NULL, 1);
    BIO_push(cipher, b64);
    BIO_push(b64, buffer);
    BIO_push(buffer, file);
    for (total = 0; total < len; total += written)
    {
        if ((written = BIO_write(cipher, out + total, len - total)) <= 0)
        {
            if (BIO_should_retry(cipher))
            {
                written = 0;
                continue;
            }
            break;
        }
    }
    BIO_flush(cipher);
    BIO_free_all(cipher);
}

I've just changed EVP_des_ede3_cbc() from the example to EVP_aes_128_gcm() - and changed the key to be 16 chars.

Upvotes: 1

Views: 901

Answers (1)

ragebiswas
ragebiswas

Reputation: 3878

Sorry, I figured this out. I was passing a NULL as IV - which is absolutely required - apparently!

Upvotes: 1

Related Questions