0

I am trying to use the <CommonCrypto/CommonHMAC.h> library in c++ on a mac to encode a string with a key in sha512. I already have a function that will encode a string into sha512, I just don't know how to do it with a key. This is the function I created where I tried to implement the key using the CommonHMAC library (it fails to do so properly obviously). I have found no documentation on how to do this in c++, if anyone knows please help.

#include <CommonCrypto/CommonHMAC.h>

std::string sha512_encoder(std::string secret, std::string data){
    const char *s = secret.c_str();
    const char *m = data.c_str();
    char* result = (char*)malloc(sizeof(char)*64);
    size_t dataSize = (size_t)(sizeof(char)*(strlen(m)));
    size_t secretSize = (size_t)(sizeof(char)*(strlen(s)));
    CCHmac(kCCHmacAlgSHA512, s, secretSize, m, dataSize, result);
    return result;
}
Sam Moldenha
  • 463
  • 2
  • 11

1 Answers1

2

Don't do heap allocation for the result and you must convert bytes to human-readable hexadecimal string.

std::string sha512_encoder(std::string secret, std::string data){
    unsigned char result[CC_SHA512_DIGEST_LENGTH];
    CCHmac(kCCHmacAlgSHA512, secret.c_str(), secret.length(), data.c_str(), data.length(), result);
    char sha512_str[128];
    for (int i = 0; i < 64; i++)
        sprintf(&sha512_str[i * 2], "%02x", (unsigned int) result[i]);
    return std::string(sha512_str);
}
msg
  • 136
  • 3