C++ PBKDF2 问题

C++ PBKDF2 Issue

我有以下功能:

void PBKDF2_HMAC_SHA_512_string(const char* pass, const char* salt, int32_t iterations, uint32_t HashLength, char* out) {
    unsigned int i;
    HashLength = HashLength / 2;
    unsigned char* digest = new unsigned char[HashLength];
    PKCS5_PBKDF2_HMAC(pass, strlen(pass), (const unsigned char*)salt, strlen(salt), iterations, EVP_sha512(), HashLength, digest);
    for (i = 0; i < sizeof(digest); i++) {
        sprintf(out + (i * 2), "%02x", 255 & digest[i]);
    }
}

当我像下面这样调用函数时,我希望得到长度为 2400 的散列,但是 returns 我 16:

char PBKDF2Hash[1025]; //[=11=] terminating space?
memset(PBKDF2Hash, 0, sizeof(PBKDF2Hash));
PBKDF2_HMAC_SHA_512_string("Password", "0123456789123456", 3500, 1024, PBKDF2Hash);
//PBKDF2Hash is now always 16 long -> strlen(PBKDF2Hash),
//while I expect it to be 2400 long?
//How is this possible and why is this happening?
//I can't figure it out

由于digest是一个pointersizeof(digest)不会给出数组的长度。根据不同的平台,sizeof(digest) 可能给你 4 或 8,这不是你想要的。也许你应该使用 for (i = 0; i < HashLength; i++).

您的代码的另一个无关问题是,digest 未在 PBKDF2_HMAC_SHA_512_string 中删除,这导致 memory leak