forked from cppalliance/http
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbcrypt.hpp
More file actions
684 lines (546 loc) · 15 KB
/
bcrypt.hpp
File metadata and controls
684 lines (546 loc) · 15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
//
// Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/cppalliance/http
//
/** @file
bcrypt password hashing library.
This header provides bcrypt password hashing with three API tiers:
**Tier 1 -- Synchronous** (low-level, no capy dependency):
@code
bcrypt::result r = bcrypt::hash("password", 12);
system::error_code ec;
bool ok = bcrypt::compare("password", r.str(), ec);
@endcode
**Tier 2 -- Capy Task** (lazy coroutine, caller controls executor):
@code
auto r = co_await bcrypt::hash_task("password", 12);
@endcode
**Tier 3 -- Friendly Async** (auto-offloads to system thread pool):
@code
auto r = co_await bcrypt::hash_async("password", 12);
bool ok = co_await bcrypt::compare_async("password", r.str());
@endcode
*/
#ifndef BOOST_HTTP_BCRYPT_HPP
#define BOOST_HTTP_BCRYPT_HPP
#include <boost/http/detail/config.hpp>
#include <boost/http/detail/except.hpp>
#include <boost/core/detail/string_view.hpp>
#include <boost/system/error_category.hpp>
#include <boost/system/error_code.hpp>
#include <boost/system/is_error_code_enum.hpp>
#include <boost/capy/task.hpp>
#include <boost/capy/ex/executor_ref.hpp>
#include <boost/capy/ex/io_env.hpp>
#include <boost/capy/ex/run_async.hpp>
#include <boost/capy/ex/system_context.hpp>
#include <cstddef>
#include <cstring>
#include <exception>
#include <string>
#include <system_error>
namespace boost {
namespace http {
namespace bcrypt {
//------------------------------------------------
/** bcrypt hash version prefix.
The version determines which variant of bcrypt is used.
All versions produce compatible hashes.
*/
enum class version
{
/// $2a$ - Original specification
v2a,
/// $2b$ - Fixed handling of passwords > 255 chars (recommended)
v2b
};
//------------------------------------------------
/** Error codes for bcrypt operations.
These errors indicate malformed input from untrusted sources.
*/
enum class error
{
/// Success
ok = 0,
/// Salt string is malformed
invalid_salt,
/// Hash string is malformed
invalid_hash
};
} // bcrypt
} // http
namespace system {
template<>
struct is_error_code_enum<
::boost::http::bcrypt::error>
{
static bool const value = true;
};
} // system
} // boost
namespace std {
template<>
struct is_error_code_enum<
::boost::http::bcrypt::error>
: std::true_type {};
} // std
namespace boost {
namespace http {
namespace bcrypt {
namespace detail {
struct BOOST_SYMBOL_VISIBLE
error_cat_type
: system::error_category
{
BOOST_HTTP_DECL const char* name(
) const noexcept override;
BOOST_HTTP_DECL std::string message(
int) const override;
BOOST_HTTP_DECL char const* message(
int, char*, std::size_t
) const noexcept override;
BOOST_SYSTEM_CONSTEXPR error_cat_type()
: error_category(0xbc8f2a4e7c193d56)
{
}
};
BOOST_HTTP_DECL extern
error_cat_type error_cat;
} // detail
inline
BOOST_SYSTEM_CONSTEXPR
system::error_code
make_error_code(
error ev) noexcept
{
return system::error_code{
static_cast<std::underlying_type<
error>::type>(ev),
detail::error_cat};
}
//------------------------------------------------
/** Fixed-size buffer for bcrypt hash output.
Stores a bcrypt hash string (max 60 chars) in an
inline buffer with no heap allocation.
@par Example
@code
bcrypt::result r = bcrypt::hash("password", 10);
core::string_view sv = r; // or r.str()
std::cout << r.c_str(); // null-terminated
@endcode
*/
class result
{
char buf_[61];
unsigned char size_;
public:
/** Default constructor.
Constructs an empty result.
*/
result() noexcept
: size_(0)
{
buf_[0] = '\0';
}
/** Return the hash as a string_view.
*/
core::string_view
str() const noexcept
{
return core::string_view(buf_, size_);
}
/** Implicit conversion to string_view.
*/
operator core::string_view() const noexcept
{
return str();
}
/** Return null-terminated C string.
*/
char const*
c_str() const noexcept
{
return buf_;
}
/** Return pointer to data.
*/
char const*
data() const noexcept
{
return buf_;
}
/** Return size in bytes (excludes null terminator).
*/
std::size_t
size() const noexcept
{
return size_;
}
/** Check if result is empty.
*/
bool
empty() const noexcept
{
return size_ == 0;
}
/** Check if result contains valid data.
*/
explicit
operator bool() const noexcept
{
return size_ != 0;
}
private:
friend BOOST_HTTP_DECL result gen_salt(unsigned, version);
friend BOOST_HTTP_DECL result hash(core::string_view, unsigned, version);
friend BOOST_HTTP_DECL result hash(core::string_view, core::string_view, system::error_code&);
char* buf() noexcept { return buf_; }
void set_size(unsigned char n) noexcept
{
size_ = n;
buf_[n] = '\0';
}
};
//------------------------------------------------
/** Generate a random salt.
Creates a bcrypt salt string suitable for use with
the hash() function.
@par Preconditions
@code
rounds >= 4 && rounds <= 31
@endcode
@par Exception Safety
Strong guarantee.
@par Complexity
Constant.
@param rounds Cost factor. Each increment doubles the work.
Default is 10, which takes approximately 100ms on modern hardware.
@param ver Hash version to use.
@return A 29-character salt string.
@throws std::invalid_argument if rounds is out of range.
@throws system_error on RNG failure.
*/
BOOST_HTTP_DECL
result
gen_salt(
unsigned rounds = 10,
version ver = version::v2b);
/** Hash a password with auto-generated salt.
Generates a random salt and hashes the password.
@par Preconditions
@code
rounds >= 4 && rounds <= 31
@endcode
@par Exception Safety
Strong guarantee.
@par Complexity
O(2^rounds).
@param password The password to hash. Only the first 72 bytes
are used (bcrypt limitation).
@param rounds Cost factor. Each increment doubles the work.
@param ver Hash version to use.
@return A 60-character hash string.
@throws std::invalid_argument if rounds is out of range.
@throws system_error on RNG failure.
*/
BOOST_HTTP_DECL
result
hash(
core::string_view password,
unsigned rounds = 10,
version ver = version::v2b);
/** Hash a password using a provided salt.
Uses the given salt to hash the password. The salt should
be a string previously returned by gen_salt() or extracted
from a hash string.
@par Exception Safety
Strong guarantee.
@par Complexity
O(2^rounds).
@param password The password to hash.
@param salt The salt string (29 characters).
@param ec Set to bcrypt::error::invalid_salt if the salt
is malformed.
@return A 60-character hash string, or empty result on error.
*/
BOOST_HTTP_DECL
result
hash(
core::string_view password,
core::string_view salt,
system::error_code& ec);
/** Compare a password against a hash.
Extracts the salt from the hash, re-hashes the password,
and compares the result.
@par Exception Safety
Strong guarantee.
@par Complexity
O(2^rounds).
@param password The plaintext password to check.
@param hash The hash string to compare against.
@param ec Set to bcrypt::error::invalid_hash if the hash
is malformed.
@return true if the password matches the hash, false if
it does not match OR if an error occurred. Always check
ec to distinguish between a mismatch and an error.
*/
BOOST_HTTP_DECL
bool
compare(
core::string_view password,
core::string_view hash,
system::error_code& ec);
/** Extract the cost factor from a hash string.
@par Exception Safety
Strong guarantee.
@par Complexity
Constant.
@param hash The hash string to parse.
@param ec Set to bcrypt::error::invalid_hash if the hash
is malformed.
@return The cost factor (4-31) on success, or 0 if an
error occurred.
*/
BOOST_HTTP_DECL
unsigned
get_rounds(
core::string_view hash,
system::error_code& ec);
namespace detail {
// bcrypt truncates passwords to 72 bytes
struct password_buf
{
char data_[72];
unsigned char size_;
explicit password_buf(
core::string_view s) noexcept
: size_(static_cast<unsigned char>(
(std::min)(s.size(), std::size_t{72})))
{
std::memcpy(data_, s.data(), size_);
}
operator core::string_view() const noexcept
{
return {data_, size_};
}
};
// bcrypt hashes are always 60 characters
struct hash_buf
{
char data_[61];
unsigned char size_;
explicit hash_buf(
core::string_view s) noexcept
: size_(static_cast<unsigned char>(
(std::min)(s.size(), std::size_t{60})))
{
std::memcpy(data_, s.data(), size_);
data_[size_] = '\0';
}
operator core::string_view() const noexcept
{
return {data_, size_};
}
};
} // detail
//------------------------------------------------
/** Hash a password, returning a lazy task.
Returns a @ref capy::task that wraps the synchronous
hash() call. The caller can co_await this task directly
or launch it on a specific executor via run_async().
@par Example
@code
// co_await in current context
bcrypt::result r = co_await bcrypt::hash_task("password", 12);
// or launch on a specific executor
run_async(my_executor)(bcrypt::hash_task("password", 12));
@endcode
@param password The password to hash.
@param rounds Cost factor. Each increment doubles the work.
@param ver Hash version to use.
@return A lazy task yielding `result`.
@throws std::invalid_argument if rounds is out of range.
@throws system_error on RNG failure.
*/
inline
capy::task<result>
hash_task(
core::string_view password,
unsigned rounds = 10,
version ver = version::v2b)
{
detail::password_buf pw(password);
co_return hash(pw, rounds, ver);
}
/** Compare a password against a hash, returning a lazy task.
Returns a @ref capy::task that wraps the synchronous
compare() call. Errors are translated to exceptions.
@par Example
@code
bool ok = co_await bcrypt::compare_task("password", stored_hash);
@endcode
@param password The plaintext password to check.
@param hash_str The hash string to compare against.
@return A lazy task yielding `bool`.
@throws system_error if the hash is malformed.
*/
inline
capy::task<bool>
compare_task(
core::string_view password,
core::string_view hash_str)
{
detail::password_buf pw(password);
detail::hash_buf hs(hash_str);
system::error_code ec;
bool ok = compare(pw, hs, ec);
if(ec.failed())
http::detail::throw_system_error(ec);
co_return ok;
}
//------------------------------------------------
namespace detail {
struct hash_async_op
{
password_buf password_;
unsigned rounds_;
version ver_;
result result_;
std::exception_ptr ep_;
bool await_ready() const noexcept
{
return false;
}
void await_suspend(
std::coroutine_handle<void> cont,
capy::io_env const* env)
{
auto caller_ex = env->executor;
auto& pool = capy::get_system_context();
auto sys_ex = pool.get_executor();
capy::run_async(sys_ex,
[this, cont, caller_ex]
(result r) mutable
{
result_ = r;
caller_ex.dispatch(cont).resume();
},
[this, cont, caller_ex]
(std::exception_ptr ep) mutable
{
ep_ = ep;
caller_ex.dispatch(cont).resume();
}
)(hash_task(password_, rounds_, ver_));
}
result await_resume()
{
if(ep_)
std::rethrow_exception(ep_);
return result_;
}
};
struct compare_async_op
{
password_buf password_;
hash_buf hash_str_;
bool result_ = false;
std::exception_ptr ep_;
bool await_ready() const noexcept
{
return false;
}
void await_suspend(
std::coroutine_handle<void> cont,
capy::io_env const* env)
{
auto caller_ex = env->executor;
auto& pool = capy::get_system_context();
auto sys_ex = pool.get_executor();
capy::run_async(sys_ex,
[this, cont, caller_ex]
(bool ok) mutable
{
result_ = ok;
caller_ex.dispatch(cont).resume();
},
[this, cont, caller_ex]
(std::exception_ptr ep) mutable
{
ep_ = ep;
caller_ex.dispatch(cont).resume();
}
)(compare_task(password_, hash_str_));
}
bool await_resume()
{
if(ep_)
std::rethrow_exception(ep_);
return result_;
}
};
} // detail
/** Hash a password asynchronously on the system thread pool.
Returns an awaitable that offloads the CPU-intensive
bcrypt work to the system thread pool, then resumes
the caller on their original executor. Modeled after
Express.js: `await bcrypt.hash(password, 12)`.
@par Example
@code
bcrypt::result r = co_await bcrypt::hash_async("my_password", 12);
@endcode
@param password The password to hash.
@param rounds Cost factor. Each increment doubles the work.
@param ver Hash version to use.
@return An awaitable yielding `result`.
@throws std::invalid_argument if rounds is out of range.
@throws system_error on RNG failure.
*/
inline
detail::hash_async_op
hash_async(
core::string_view password,
unsigned rounds = 10,
version ver = version::v2b)
{
return detail::hash_async_op{
detail::password_buf(password),
rounds,
ver,
{},
{}};
}
/** Compare a password against a hash asynchronously.
Returns an awaitable that offloads the CPU-intensive
bcrypt work to the system thread pool, then resumes
the caller on their original executor. Modeled after
Express.js: `await bcrypt.compare(password, hash)`.
@par Example
@code
bool ok = co_await bcrypt::compare_async("my_password", stored_hash);
@endcode
@param password The plaintext password to check.
@param hash_str The hash string to compare against.
@return An awaitable yielding `bool`.
@throws system_error if the hash is malformed.
*/
inline
detail::compare_async_op
compare_async(
core::string_view password,
core::string_view hash_str)
{
return detail::compare_async_op{
detail::password_buf(password),
detail::hash_buf(hash_str),
false,
{}};
}
} // bcrypt
} // http
} // boost
#endif