Skip to content

Instantly share code, notes, and snippets.

@yoshiki
Last active June 24, 2021 12:00
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yoshiki/812d35a32bcf175f11cb952ed9d1582a to your computer and use it in GitHub Desktop.
Save yoshiki/812d35a32bcf175f11cb952ed9d1582a to your computer and use it in GitHub Desktop.
#include <openssl/hmac.h>
#include <string.h>
#include <stdio.h>
int main()
{
unsigned char *key = (unsigned char*)"This is your secret";
unsigned char *data = (unsigned char*) "hoge";
unsigned char *expected = (unsigned char*) "4a7bc6c59ebc1a83dc38ec4fd537f98994a9210bf09ad9fc8c60c2ae83746d82";
unsigned char *result;
int result_len = 32;
int i;
static char res_hexstring[64];
result = HMAC(EVP_sha256(), key, strlen((char *)key), data, strlen((char *)data), NULL, NULL);
for (i = 0; i < result_len; i++) {
sprintf(&(res_hexstring[i * 2]), "%02x", result[i]);
}
if (strcmp((char *) res_hexstring, (char *) expected) == 0) {
printf("Got %s\nTest ok, result length %d\n", res_hexstring, result_len);
} else {
printf("Got %s instead of %s\n", res_hexstring, expected);
}
}
@ddolsoon
Copy link

@yoshiki, thank you for the good code.
However, the size of the res_hexstring array is incorrectly declared.
Here is the revised code, so please refer to it.

#include <openssl/hmac.h>
#include <string.h>
#include <stdio.h>

int main()
{
  unsigned char *key = (unsigned char*)"This is your secret";
  unsigned char *data = (unsigned char*) "hoge";
  unsigned char *expected = (unsigned char*) "4a7bc6c59ebc1a83dc38ec4fd537f98994a9210bf09ad9fc8c60c2ae83746d82";
  unsigned char *result;
  int result_len = 32;
  int i;
  static char res_hexstring[64];

  result = HMAC(EVP_sha256(), key, strlen((char *)key), data, strlen((char *)data), NULL, NULL);
  for (i = 0; i < result_len; i++) {
    sprintf(&(res_hexstring[i * 2]), "%02x", result[i]);
  }

  if (strcmp((char *) res_hexstring, (char *) expected) == 0) {
    printf("Got %s\nTest ok, result length %d\n", res_hexstring, result_len);
  } else {
    printf("Got %s instead of %s\n", res_hexstring, expected);
  }
}

@yoshiki
Copy link
Author

yoshiki commented Feb 5, 2021

@ddolsoon
Thank you for your comment!
I have incorporated your changes.

@shmn18
Copy link

shmn18 commented Apr 19, 2021

@yoshiki Hi I'm using Openssl version 3.0.0. And I get an error, when I try to compile the code. The error is as follows.

kdf_ck.c: In function ‘main’:
kdf_ck.c:15:3: warning: ‘HMAC’ is deprecated: Since OpenSSL 3.0 [-Wdeprecated-declarations]
result = HMAC(EVP_sha256(), key, strlen((char *)key), data, strlen((char *)data), NULL, NULL);
^~~~~~
In file included from kdf_ck.c:1:0:
/usr/local/include/openssl/hmac.h:48:38: note: declared here
OSSL_DEPRECATEDIN_3_0 unsigned char *HMAC(const EVP_MD *evp_md, const void *key,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment