mercredi 4 avril 2018

Converting data from unsigned char* to string

I have this code:

string HMACsha256(string message, string APIkey){

    // The secret key for hashing
    char key[APIkey.length() + 1];
    strcpy(key, APIkey.c_str());

    // The data that we're going to hash
    char data[message.length() + 1];
    strcpy(data, message.c_str());

    unsigned char* result;
    unsigned int len = 64;

    result = (unsigned char*)malloc(sizeof(char) * len);

    HMAC_CTX ctx;
    HMAC_CTX_init(&ctx);

    HMAC_Init_ex(&ctx, key, strlen(key), EVP_sha256(), NULL);
    HMAC_Update(&ctx, (unsigned char*)&data, strlen(data));
    HMAC_Final(&ctx, result, &len);
    HMAC_CTX_cleanup(&ctx);

    printf("HMAC digest: ");

    string signature; // <-------- I want to store result in this

    for (int i = 0; i != len; i++){
        printf("%02x", (unsigned int)result[i]);
    }

    cout << endl<<  "SIG: " << signature << endl;

    free(result);

    return signature;
}

Everything about it works fine, except I need to be able to return the result as a string. I've been unable to come up with a way to take the data from the unsigned char* result variable and store it into the signature string. Does anyone know how I can go about this?

Aucun commentaire:

Enregistrer un commentaire