Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- bool hashlib_PBKDF2(const uint8_t* password, size_t plen, uint8_t* out, const uint8_t* salt, size_t salt_len, size_t iter_count, size_t keylen){
- uint8_t sha_buffer[SHA256_OUTSIZE];
- uint8_t sha_comp[SHA256_OUTSIZE];
- size_t outlen;
- SHA256_CTX ctx;
- uint32_t mbuffer[64];
- uint32_t counter = 1;
- if(password==NULL || out==NULL) return false;
- if(plen==0) return false;
- if(iter_count<1) return false;
- if(keylen==0) return false;
- //HASH = sha256
- // DK = T(i) for i in 0 => (keylen/HASH), concat
- for(outlen = 0; outlen < keylen; outlen+=SHA256_OUTSIZE, counter++){
- //T(i) = F(password, salt, c, i) = U1 xor U2 xor ... xor Uc
- //U1 = PRF1(Password, Salt + INT_32_BE(i))
- //U2 = PRF(Password, U1)
- //⋮
- //Uc = PRF(Password, Uc)
- size_t copylen = ((keylen-outlen) > SHA256_OUTSIZE) ? SHA256_OUTSIZE : keylen-outlen;
- uint8_t c[4];
- c[0] = (counter >> 24) & 0xff;
- c[1] = (counter >> 16) & 0xff;
- c[2] = (counter >> 8) & 0xff;
- c[3] = (counter >> 0) & 0xff;
- hashlib_Sha256Init(&ctx, mbuffer);
- hashlib_Sha256Update(&ctx, password, plen);
- hashlib_Sha256Update(&ctx, salt, salt_len);
- hashlib_Sha256Update(&ctx, c, sizeof c);
- hashlib_Sha256Final(&ctx, sha_comp);
- for(size_t ic=1; ic<iter_count; ic++){
- hashlib_Sha256Init(&ctx, NULL);
- hashlib_Sha256Update(&ctx, password, plen);
- hashlib_Sha256Update(&ctx, sha_comp, SHA256_OUTSIZE);
- hashlib_Sha256Final(&ctx, sha_buffer);
- for(uint8_t j=0; j<SHA256_OUTSIZE; j++)
- sha_comp[j] ^= sha_buffer[j];
- }
- memcpy(&out[outlen], sha_comp, copylen);
- }
- return true;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement