Advertisement
AnthonyCagliano

Untitled

Jan 12th, 2022
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. 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){
  2.  
  3. uint8_t sha_buffer[SHA256_OUTSIZE];
  4. uint8_t sha_comp[SHA256_OUTSIZE];
  5. size_t outlen;
  6. SHA256_CTX ctx;
  7. uint32_t mbuffer[64];
  8. uint32_t counter = 1;
  9.  
  10. if(password==NULL || out==NULL) return false;
  11. if(plen==0) return false;
  12. if(iter_count<1) return false;
  13. if(keylen==0) return false;
  14. //HASH = sha256
  15. // DK = T(i) for i in 0 => (keylen/HASH), concat
  16.  
  17. for(outlen = 0; outlen < keylen; outlen+=SHA256_OUTSIZE, counter++){
  18. //T(i) = F(password, salt, c, i) = U1 xor U2 xor ... xor Uc
  19. //U1 = PRF1(Password, Salt + INT_32_BE(i))
  20. //U2 = PRF(Password, U1)
  21. //⋮
  22. //Uc = PRF(Password, Uc)
  23. size_t copylen = ((keylen-outlen) > SHA256_OUTSIZE) ? SHA256_OUTSIZE : keylen-outlen;
  24. uint8_t c[4];
  25. c[0] = (counter >> 24) & 0xff;
  26. c[1] = (counter >> 16) & 0xff;
  27. c[2] = (counter >> 8) & 0xff;
  28. c[3] = (counter >> 0) & 0xff;
  29. hashlib_Sha256Init(&ctx, mbuffer);
  30. hashlib_Sha256Update(&ctx, password, plen);
  31. hashlib_Sha256Update(&ctx, salt, salt_len);
  32. hashlib_Sha256Update(&ctx, c, sizeof c);
  33. hashlib_Sha256Final(&ctx, sha_comp);
  34. for(size_t ic=1; ic<iter_count; ic++){
  35. hashlib_Sha256Init(&ctx, NULL);
  36. hashlib_Sha256Update(&ctx, password, plen);
  37. hashlib_Sha256Update(&ctx, sha_comp, SHA256_OUTSIZE);
  38. hashlib_Sha256Final(&ctx, sha_buffer);
  39. for(uint8_t j=0; j<SHA256_OUTSIZE; j++)
  40. sha_comp[j] ^= sha_buffer[j];
  41. }
  42. memcpy(&out[outlen], sha_comp, copylen);
  43. }
  44. return true;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement