I want to compute a CMAC using OpenSSL. I found this question which helped me.
But I am encountering a problem with the following code:
#include <openssl/cmac.h>
void dispHex(const unsigned char *buffer, unsigned int size) {
int i=0;
for (i=0; i<size-1; i++) {
printf("%02X ", buffer[i]);
}
printf("%02x\n", buffer[i]);
}
int main() {
size_t out_len;
unsigned char res[16];
unsigned char mac_key[16] = { 0x00, 0x01 ,0x02 ,0x03, 0x04, 0x05, 0x06, 0x07,
0x00, 0x01 ,0x02 ,0x03, 0x04, 0x05, 0x06, 0x07};
unsigned char msg[16] = { 0x00, 0x01 ,0x02 ,0x03, 0x04, 0x05, 0x06, 0x07,
0x00, 0x01 ,0x02 ,0x03, 0x04, 0x05, 0x06, 0x07};
CMAC_CTX *cmac = CMAC_CTX_new();
CMAC_Init(cmac, mac_key, 16, EVP_aes_128_cbc(), NULL);
CMAC_Update(cmac, msg, sizeof(msg));
CMAC_Final(cmac, res, &out_len);
dispHex(res, sizeof(res));
return 0;
}
I compile it with gcc -o test_cmac test_cmac_openssl.c -L C:/OpenSSL-Win32 -llibeay32 -I C:/OpenSSL-Win32/include
and it produces test_cmac.exe
without problem.
but when I run it (./test_cmac.exe
), nothing happens. It just prints an empty line and stops:
xxx@DESKTOP /cygdrive/e/
$ ./test_cmac.exe
xx@DESKTOP /cygdrive/e/
Even if I add printf("...");
before the CMAC computation it goes the same way.
What is strange is that the following program:
#include <openssl/hmac.h>
void dispHex(const unsigned char *buffer, unsigned int size) {
int i=0;
for (i=0; i<size-1; i++) {
printf("%02X ", buffer[i]);
}
printf("%02X\n", buffer[i]);
}
int main() {
size_t out_len;
unsigned char res[32];
unsigned char mac_key[16] = { 0x00, 0x01 ,0x02 ,0x03, 0x04, 0x05, 0x06, 0x07,
0x00, 0x01 ,0x02 ,0x03, 0x04, 0x05, 0x06, 0x07};
unsigned char msg[16] = { 0x00, 0x01 ,0x02 ,0x03, 0x04, 0x05, 0x06, 0x07,
0x00, 0x01 ,0x02 ,0x03, 0x04, 0x05, 0x06, 0x07};
HMAC_CTX hmac;
HMAC_CTX_init(&hmac);
HMAC_Init_ex(&hmac, mac_key, 16, EVP_sha256(), NULL);
HMAC_Update(&hmac, msg, sizeof(msg));
HMAC_Final(&hmac, res, &out_len);
dispHex(res, sizeof(res));
return 0;
}
runs normally: after gcc -o test_hmac test_hmac_openssl.c -L C:/OpenSSL-Win32 -llibeay32 -I C:/OpenSSL-Win32/include
and ./test_hmac.exe
I get:
xxx@DESKTOP /cygdrive/e/
$ ./test_hmac.exe
...9A 21 F8 2D 60 84 6C 09 08 98 A5 1F 23 8C C8 8F C4 A9 0C C4 49 45 DA 10 B9 39 C0 93 C3 10 60 BE
xxx@DESKTOP /cygdrive/e/
So I'm a little confused... Why does it works with the HMAC primitive but not with the CMAC one? Does anybody already encountered this kind of problem?
I am using OpenSSL 32bit version: openssl version
returns OpenSSL 1.0.2e 3 Dec 2015
.
I also checked that C:\OpenSSL-Win32\
is declared in the PATH environment variable.