| 46 | |
| 47 | template <class T> |
| 48 | word32 PBKDF2_HMAC<T>::DeriveKey(byte* derived, word32 dLen, const byte* pwd, |
| 49 | word32 pLen, const byte* salt, word32 sLen, |
| 50 | word32 iterations) const |
| 51 | { |
| 52 | if (dLen > MaxDerivedKeyLength()) |
| 53 | return 0; |
| 54 | |
| 55 | ByteBlock buffer(T::DIGEST_SIZE); |
| 56 | HMAC<T> hmac; |
| 57 | |
| 58 | hmac.SetKey(pwd, pLen); |
| 59 | |
| 60 | word32 i = 1; |
| 61 | |
| 62 | while (dLen > 0) { |
| 63 | hmac.Update(salt, sLen); |
| 64 | word32 j; |
| 65 | for (j = 0; j < 4; j++) { |
| 66 | byte b = i >> ((3-j)*8); |
| 67 | hmac.Update(&b, 1); |
| 68 | } |
| 69 | hmac.Final(buffer.get_buffer()); |
| 70 | |
| 71 | word32 segmentLen = min(dLen, buffer.size()); |
| 72 | memcpy(derived, buffer.get_buffer(), segmentLen); |
| 73 | |
| 74 | for (j = 1; j < iterations; j++) { |
| 75 | hmac.Update(buffer.get_buffer(), buffer.size()); |
| 76 | hmac.Final(buffer.get_buffer()); |
| 77 | xorbuf(derived, buffer.get_buffer(), segmentLen); |
| 78 | } |
| 79 | derived += segmentLen; |
| 80 | dLen -= segmentLen; |
| 81 | i++; |
| 82 | } |
| 83 | return iterations; |
| 84 | } |
| 85 | |
| 86 | |
| 87 | |