Skip to content

Commit e11be12

Browse files
authored
docs: document PBKDF2 usage
2 parents bb97f7d + 2fd752f commit e11be12

2 files changed

Lines changed: 57 additions & 61 deletions

File tree

README-RU.md

Lines changed: 30 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -155,22 +155,42 @@ std::vector<uint8_t> get_hmac(
155155

156156
Возвращает: Бинарный HMAC в виде `std::vector<uint8_t>`
157157

158-
### PBKDF2 (RFC 8018)
158+
### PBKDF2
159+
160+
PBKDF2 преобразует пароль пользователя в криптографический ключ.
161+
Используется для шифрования и хранения хешей паролей.
159162

160163
```cpp
161164
#include <hmac_cpp/hmac_utils.hpp>
162-
163-
std::string password = "password";
164-
std::vector<uint8_t> salt(16, 0x01);
165-
std::vector<uint8_t> dk = hmac::pbkdf2(password, salt, 1000, 32);
165+
auto salt = hmac::random_bytes(16);
166+
auto key = hmac::pbkdf2_hmac_sha256(password, salt, iters, 32);
166167
```
167168

168-
Параметры:
169+
Рекомендации:
170+
171+
- **Соль:** случайные 16–32 байта.
172+
- **Итерации:** подбирайте число так, чтобы вычисление занимало ~100–250 мс на целевой машине.
173+
- **Длина ключа:** 32 байта.
174+
- **Алгоритм:** HMAC-SHA-256.
175+
176+
Параметры и шифротекст можно сериализовать, например, так:
177+
`magic|salt|iters|iv|ct|tag`.
178+
179+
См. `example_pbkdf2.cpp` для полноценного примера.
180+
181+
#### Рекомендуемые параметры
182+
183+
| Цель | Итерации | Длина ключа | PRF |
184+
|--------|---------:|------------:|-------------|
185+
| Desktop| 600000 | 32 байта | HMAC-SHA256 |
186+
| Laptop | 300000 | 32 байта | HMAC-SHA256 |
187+
| Mobile | 150000 | 32 байта | HMAC-SHA256 |
188+
189+
#### Примечания по безопасности
169190

170-
- `password`, `salt` — байтовые строки; `salt` должна быть уникальной и не короче 16 байт
171-
- `iterations` — число итераций (≥1), подбирается по [рекомендациям OWASP](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html)
172-
- `dk_len` — длина ключа в байтах, не более `(2^32−1) * hLen`
173-
- `prf` — выбор хеша (`Sha1`, `Sha256` по умолчанию, `Sha512`)
191+
- PBKDF2 зависит от CPU и уязвим для атак с использованием GPU/ASIC, поэтому выбирайте высокое число итераций или более сильные KDF.
192+
- Каждому паролю нужна уникальная случайная соль достаточной длины.
193+
- Соль, итерации и алгоритм не являются секретом — храните их вместе с хешем или шифротекстом.
174194

175195
### 🕓 HOTP и TOTP токены
176196

README.md

Lines changed: 27 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -184,55 +184,45 @@ Parameters:
184184

185185
Returns: Binary digest as `std::vector<uint8_t>`
186186

187-
### PBKDF2 Key Derivation
187+
### PBKDF2
188+
189+
PBKDF2 derives a cryptographic key from a user password. It is typically
190+
used to unlock encrypted data or verify password hashes.
188191

189192
```cpp
190193
#include <hmac_cpp/hmac_utils.hpp>
191-
192-
std::string password = "password";
193-
std::vector<uint8_t> salt(16, 0x01); // at least 16 bytes
194-
std::vector<uint8_t> dk = hmac::pbkdf2(password, salt, 1000, 32);
195-
hmac::Pbkdf2Result stored{salt, 1000, dk};
196-
auto verify = hmac::pbkdf2(password, stored);
197-
bool ok = hmac::constant_time_equals(verify.key, stored.key);
194+
auto salt = hmac::random_bytes(16);
195+
auto key = hmac::pbkdf2_hmac_sha256(password, salt, iters, 32);
198196
```
199197

200-
Parameters:
201-
202-
- `password`, `salt` — Raw byte arrays. `salt` must be **>=16 bytes** and unique.
203-
- `iterations` — Number of iterations (>=1). Tune according to the
204-
[OWASP Password Storage Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html).
205-
- `dk_len` — Desired key length in bytes, up to `(2^32-1) * hLen` (RFC 8018).
206-
- `prf` — Optional hash (`Sha1`, `Sha256` default, `Sha512`).
207-
208-
⚠️ Low iteration counts or short salts reduce security.
198+
Recommendations:
209199

210-
For deployments with a server-side *pepper*, use `pbkdf2_with_pepper(password, salt, pepper, iters, dkLen)`.
211-
The pepper is a secret key stored separately from the hashed password.
200+
- **Salt:** 16–32 random bytes.
201+
- **Iterations:** pick a value so derivation takes ~100–250 ms on the target
202+
machine.
203+
- **Derived key length:** 32 bytes.
204+
- **Algorithm:** HMAC-SHA-256.
212205

213-
### PBKDF2 Security Notes
206+
Parameters and ciphertext may be serialized as:
207+
`magic|salt|iters|iv|ct|tag`.
214208

215-
- Use a random salt of **at least 16 bytes** and never reuse it.
216-
- Choose an iteration count that takes roughly **200–500 ms** on your target hardware (~2025).
217-
- Store `{salt, iterations}` alongside the ciphertext or hash; these values are public.
218-
- Salts and iteration counts must be unique per password.
219-
- Example serialization: `{magic|ver|prf|salt|iters|dkLen|…}`.
209+
See `example_pbkdf2.cpp` for a complete example.
220210

221-
#### PBKDF2-HMAC-SHA256 + AES-GCM
211+
#### Recommended Parameters
222212

223-
```cpp
224-
#include <hmac_cpp/hmac_utils.hpp>
225-
#include <aes_cpp/aes_utils.hpp>
213+
| Target | Iterations | Derived key length | PRF |
214+
|---------|-----------:|------------------:|-----|
215+
| Desktop | 600000 | 32 bytes | HMAC-SHA256 |
216+
| Laptop | 300000 | 32 bytes | HMAC-SHA256 |
217+
| Mobile | 150000 | 32 bytes | HMAC-SHA256 |
226218

227-
std::string password = "correct horse battery staple";
228-
std::vector<uint8_t> salt(16, 0x00); // 16 random bytes
229-
auto key = hmac::pbkdf2(password, salt, 100000, 32, hmac::Pbkdf2Hash::Sha256);
219+
#### Security Notes
230220

231-
std::string plaintext = "secret";
232-
std::vector<uint8_t> aad = {'h','e','a','d','e','r'};
233-
auto pkt = aes_cpp::utils::encrypt_gcm(plaintext, key, aad);
234-
auto restored = aes_cpp::utils::decrypt_gcm_to_string(pkt, key, aad);
235-
```
221+
- PBKDF2 is CPU-bound and vulnerable to massive GPU/ASIC brute force.
222+
Choose high iteration counts or stronger KDFs.
223+
- Every password requires a unique, random salt of sufficient length.
224+
- Salts, iteration counts, and algorithms are not secrets—store them
225+
alongside the hash or ciphertext.
236226

237227
### HKDF (RFC 5869)
238228

@@ -339,20 +329,6 @@ int main() {
339329
**Note:** avoid checking input lengths before calling `constant_time_equal`.
340330
Early length comparisons can leak information through timing side channels.
341331

342-
## PBKDF2 Recommended Parameters
343-
344-
| Target | Iterations | Derived key length | PRF |
345-
|---------|-----------:|------------------:|-----|
346-
| Desktop | 600000 | 32 bytes | HMAC-SHA256 |
347-
| Laptop | 300000 | 32 bytes | HMAC-SHA256 |
348-
| Mobile | 150000 | 32 bytes | HMAC-SHA256 |
349-
350-
## Security Notes
351-
352-
- PBKDF2 is CPU-bound and vulnerable to massive GPU/ASIC brute force. Choose high iteration counts or stronger KDFs.
353-
- Every password requires a unique, random salt of sufficient length.
354-
- Salts, iteration counts, and algorithms are not secrets—store them alongside the hash for verification.
355-
356332
## 📚 Resources
357333

358334
* Original [SHA256 implementation](http://www.zedwood.com/article/cpp-sha256-function)

0 commit comments

Comments
 (0)