Created
January 22, 2023 18:26
-
-
Save devendranaga/04cccd0417c51f244f652399b7e63bf3 to your computer and use it in GitHub Desktop.
GMAC openssl example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include <stdint.h> | |
#include <openssl/evp.h> | |
int main() | |
{ | |
int ret = 0, unused = 0; | |
uint8_t key[] = { | |
0x77, 0xbe, 0x63, 0x70, 0x89, 0x71, 0xc4, 0xe2, | |
0x40, 0xd1, 0xcb, 0x79, 0xe8, 0xd7, 0x7f, 0xeb | |
}; | |
uint8_t iv[] = { 0xe0, 0xe0, 0x0f, 0x19, 0xfe, 0xd7, 0xba, 0x01, | |
0x36, 0xa7, 0x97, 0xf3 }; | |
uint8_t aad[] = { 0x7a, 0x43, 0xec, 0x1d, 0x9c, 0x0a, 0x5a, 0x78, | |
0xa0, 0xb1, 0x65, 0x33, 0xa6, 0x21, 0x3c, 0xab }; | |
uint8_t tag[16] = {0}; | |
uint8_t exp[] = { 0x20, 0x9f, 0xcc, 0x8d, 0x36, 0x75, 0xed, 0x93, | |
0x8e, 0x9c, 0x71, 0x66, 0x70, 0x9d, 0xd9, 0x46 }; | |
EVP_CIPHER_CTX *ctx = NULL; | |
ctx = EVP_CIPHER_CTX_new(); | |
if (ctx == NULL) { | |
return -1; | |
} | |
/* EVP GCM but no IV and KEY */ | |
ret = EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL); | |
if (ret != 1) { | |
return -1; | |
} | |
/* Set IV Length */ | |
ret = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, sizeof(iv), NULL); | |
if (ret != 1) { | |
return -1; | |
} | |
/* Initialize ctx with key and iv */ | |
ret = EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv); | |
if (ret != 1) { | |
return -1; | |
} | |
/* No output is required .. just calculate the MAC. */ | |
ret = EVP_EncryptUpdate(ctx, NULL, &unused, aad, sizeof(aad)); | |
if (ret != 1) { | |
return -1; | |
} | |
/* Finalize the authentication and get the tag */ | |
ret = EVP_EncryptFinal_ex(ctx, NULL, &unused); | |
if (ret != 1) { | |
return -1; | |
} | |
/* Get the output tag */ | |
ret = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, sizeof(tag), tag); | |
if (ret != 1) { | |
return -1; | |
} | |
printf("tag: "); | |
for (int i = 0; i < sizeof(tag); i ++) { | |
printf("%02x", tag[i]); | |
} | |
printf("\n"); | |
ret = memcmp(tag, exp, sizeof(tag)); | |
if (ret == 0) { | |
printf("Tags match.. GMAC operation ok\n"); | |
} else { | |
printf("Tags dont match.. GMAC operation failure\n"); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment