2

LibTom is a great comprehensive library for crypto and math operations in C/C++.

https://www.libtom.net/LibTomCrypt/

The documentation has been written from the perspective of the developer who wrote the library, so some of the examples are less than clear.

I have spent some time figuring out how to perform AES encryption and decryption using this library and thought I'd share my solutions here:

DanielG
  • 370
  • 1
  • 3
  • 15

1 Answers1

1

AES Encryption

int key_len = 32; // 256-bit key
int iv_len = 16;
unsigned long taglen;
unsigned char tag[16];

int enc_len;
unsigned char *enc_text;

register_cipher(&aes_desc);

enc_len = pt_len + 16; // Plain text + Tag length

enc_text = (unsigned char*)calloc(enc_len + 1, 1);

// For GCM there is no need to use the "adata" parameters, pass in NULL
int err = gcm_memory(find_cipher("aes"), (const unsigned char*) in_key, key_len, (const unsigned char*) in_iv, iv_len, NULL, NULL, plain_text, pt_len, enc_text, tag, &taglen, GCM_ENCRYPT);

// This is what took a while to figure out: the tag has to be manually appended to the encrypted text string
memcpy(enc_text + pt_len, tag, taglen);

AES Decryption

int key_len = 32; // 256-bit key
int iv_len = 16;
unsigned long taglen;
unsigned char tag[16];

int pt_len;
unsigned char *plain_text;

register_cipher(&aes_desc);

plain_text = (unsigned char*)calloc(enc_len, 1);

// For GCM there is no need to use the "adata" parameters, pass in NULL
err = gcm_memory(find_cipher("aes"), (const unsigned char*) in_key, key_len, (const unsigned char*) in_iv, iv_len, NULL, NULL, plain_text, enc_text_len, enc_text, tag, &taglen, GCM_DECRYPT);

pt_len = enc_text_len - 16; // Subtract taglen
Michael Mrozek
  • 169,610
  • 28
  • 168
  • 175
DanielG
  • 370
  • 1
  • 3
  • 15