Skip to content

Instantly share code, notes, and snippets.

@vladimirgamalyan
Created September 26, 2021 11:18
Show Gist options
  • Save vladimirgamalyan/4077be747d570170e15e55013768fb60 to your computer and use it in GitHub Desktop.
Save vladimirgamalyan/4077be747d570170e15e55013768fb60 to your computer and use it in GitHub Desktop.
embedtls (polarssl) aes gcm sample
void test3()
{
int ret;
const uint8_t key[16] = { 0xfe, 0x03, 0xcc, 0x7e, 0x7a, 0x59, 0x4a, 0x82, 0x6c, 0x3e, 0x1d, 0xec, 0x26, 0x5d, 0xdd, 0xcf };
const uint8_t iv[16] = { 0x3a, 0x1d, 0x70, 0x5c, 0xb0, 0xed, 0xa3, 0xad, 0xdd, 0xe8, 0x3d, 0x4b, 0x48, 0xeb, 0x26, 0xe2 };
const size_t iv_len = 12; // в тестах есть значения 12, 12, 12, 12, 8, 60
const uint8_t add_data[3] = { 42, 43, 44 };
const size_t add_data_len = 2;
uint8_t input_data[32];
for (int i = 0; i < 32; ++i)
input_data[i] = i;
const size_t dataLen = 30;
uint8_t encrypted_data[32] = { 0 };
uint8_t decrypted_data[32] = { 0 };
uint8_t tag_buffer[16] = { 0 };
uint8_t tag_buffer_enc[16] = { 0 };
const size_t tagLen = 8;
mbedtls_gcm_context ctx;
// ENCRYPT
mbedtls_gcm_init(&ctx);
ret = mbedtls_gcm_setkey(&ctx, MBEDTLS_CIPHER_ID_AES, key, 128);
//assert(ret == 0);
ret = mbedtls_gcm_crypt_and_tag(&ctx, // context
MBEDTLS_GCM_ENCRYPT, // mode
dataLen, // length
iv, // iv
iv_len, // iv len
add_data, // additional data
add_data_len, // additional data len
input_data, // plain data
encrypted_data, // output
tagLen, // tag len
tag_buffer); // tag buffer
//assert(ret == 0);
mbedtls_gcm_free(&ctx);
//encrypted_data[5] = 0xf0; // corrupt data
// DECRYPT
mbedtls_gcm_init(&ctx);
ret = mbedtls_gcm_setkey(&ctx, MBEDTLS_CIPHER_ID_AES, key, 128);
//assert(ret == 0);
ret = mbedtls_gcm_auth_decrypt(&ctx, // context
dataLen, // length
iv, // iv
iv_len, // iv len
add_data, // additional data
add_data_len, // 3
tag_buffer, // orig tag
tagLen, // tag len
encrypted_data, // inputt
decrypted_data // output
);
//assert(ret == 0);
mbedtls_gcm_free(&ctx);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment