Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the C++ equivalent of PHP's hash_hmac function?

I'm porting a PHP application to C++. The PHP application is using this function:

hash_hmac — Generate a keyed hash value using the HMAC method

If I have this code, what is it actually doing?

$sStr = hash_hmac ('sha256', $mydata,$mykey, $raw = true)

I know it encrypts some data using sha256 and my key, but how can I perform this in C++?

I've found the hmac and sha2 libraries, but am not sure if they are what I need.

like image 278
user63898 Avatar asked Sep 18 '11 13:09

user63898


1 Answers

I would consider looking into OpenSSL, a portable and complete cryptographic library (despite its name, it doesn't just do SSL). It has an HMAC library which you can surely wrap to get similar function.

Here's an example on how to use OpenSSL' HMAC library, taken from another question on StackOverflow (annotations mine):

  // Initialize HMAC object.
HMAC_CTX ctx;
HMAC_CTX_init(&ctx);

  // Set HMAC key.
HMAC_Init_ex(&ctx, key, 16, EVP_sha256(), NULL);

  // May be called repeatedly to insert all your data.
HMAC_Update(&ctx, data, 8);

  // Finish HMAC computation and fetch result.
HMAC_Final(&ctx, result, &result_len);

  // Done with HMAC object.
HMAC_CTX_cleanup(&ctx);
like image 73
André Caron Avatar answered Oct 05 '22 23:10

André Caron