Have a shared work buffer and derive the number of KDF round from size of buffer

This commit is contained in:
Juhani Krekelä 2021-04-09 20:16:54 +03:00
parent 741c0d0bb5
commit 4ec4a06776
1 changed files with 7 additions and 7 deletions

14
puer.c
View File

@ -268,9 +268,9 @@ void hmac(unsigned char output[32], unsigned char key[], size_t keylen, unsigned
finalize_hash(&state, output);
}
// KDF_ROUNDS must be at least 2
#define KDF_ROUNDS 100000
unsigned char kdf_buf[KDF_ROUNDS * 32];
unsigned char workbuf[8 * 1024 * 1024];
#define KDF_ROUNDS (sizeof(workbuf) / 32)
void kdf(unsigned char key[16], unsigned char salt[32], unsigned char passphrase[], size_t passphraselen) {
// This is based on the design of PBKDF2 but aims to be memory hard
// This is achieved by storing all the hashes in a buffer and the
@ -288,20 +288,20 @@ void kdf(unsigned char key[16], unsigned char salt[32], unsigned char passphrase
// include the counter i from PBKDF2 since we will ever only
// produce one block of output
size_t index = KDF_ROUNDS*32 - 32;
hmac(&kdf_buf[index], passphrase, passphraselen, salt, 32);
hmac(&workbuf[index], passphrase, passphraselen, salt, 32);
index -= 32;
// Walk back along the buffer, at each step hashing the previous
// hashes
while (index > 0) {
hmac(&kdf_buf[index], passphrase, passphraselen, &kdf_buf[index+32], 32);
hmac(&workbuf[index], passphrase, passphraselen, &workbuf[index+32], 32);
index -= 32;
}
hmac(kdf_buf, passphrase, passphraselen, &kdf_buf[32], 32);
hmac(workbuf, passphrase, passphraselen, &workbuf[32], 32);
// Perform the final hash
unsigned char final_hash[32];
hmac(final_hash, passphrase, passphraselen, kdf_buf, KDF_ROUNDS * 32);
hmac(final_hash, passphrase, passphraselen, workbuf, KDF_ROUNDS * 32);
// Use first 128 bits of final hash as the key
memcpy(key, final_hash, 16);