Aes-gcm using libgcrypt api in C

I play with libgcrypt (v1.6.1 on Gentoo x64) and I have already implemented (and tested the AE test vector tag) aes256-cbc and aes256-ctr. Now I look at aes256-gcm, but I have some doubts about the workflow. Below is the skeleton of a simple encryption program:

int main(void){

    unsigned char TEST_KEY[] = {0x60,0x3d,0xeb,0x10,0x15,0xca,0x71,0xbe,0x2b,0x73,0xae,0xf0,0x85,0x7d,0x77,0x81,0x1f,0x35,0x2c,0x07,0x3b,0x61,0x08,0xd7,0x2d,0x98,0x10,0xa3,0x09,0x14,0xdf,0xf4};
    unsigned char TEST_IV[] = {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f};
    unsigned char TEST_PLAINTEXT_1[] = {0x6b,0xc1,0xbe,0xe2,0x2e,0x40,0x9f,0x96,0xe9,0x3d,0x7e,0x11,0x73,0x93,0x17,0x2a};

    unsigned char cipher[16] = {0};

    int algo = -1, i;
    const char *name = "aes256";

    algo = gcry_cipher_map_name(name);

    gcry_cipher_hd_t hd;
    gcry_cipher_open(&hd, algo, GCRY_CIPHER_MODE_GCM, 0);
    gcry_cipher_setkey(hd, TEST_KEY, 32);
    gcry_cipher_setiv(hd, TEST_IV, 16);

    gcry_cipher_encrypt(hd, cipher, 16, TEST_PLAINTEXT_1, 16);
    char out[33];
    for(i=0;i<16;i++){
        sprintf(out+(i*2), "%02x", cipher[i]);
    }
    out[32] = '\0';
    printf("%s\n", out);

    gcry_cipher_close(hd);

    return 0;
}

In GCM mode, this instruction is also required:

gcry_cipher_authenticate (gcry cipher hd t h , const void * abuf , size t abuflen )
gcry_error_t gcry_cipher_gettag (gcry cipher hd t h , void * tag , size t taglen )

So, the correct encryption program workflow:

gcry_cipher_authenticate
gcry_cipher_encrypt
gcry_cipher_gettag

But I do not know:

  • abuflike salt? (so should I generate it using gcry_create_nonceor similar?)
  • If I want to encrypt a file, void *tagis that what I need to write to outfile?
+3
source share

All Articles