7#include <botan/argon2.h>
9#include <botan/exceptn.h>
10#include <botan/internal/fmt.h>
11#include <botan/internal/timer.h>
17Argon2::Argon2(uint8_t family,
size_t M,
size_t t,
size_t p) : m_family(family), m_M(M), m_t(t), m_p(p) {
18 BOTAN_ARG_CHECK(m_p >= 1 && m_p <= 128,
"Invalid Argon2 threads parameter");
19 BOTAN_ARG_CHECK(m_M >= 8 * m_p && m_M <= 8192 * 1024,
"Invalid Argon2 M parameter");
20 BOTAN_ARG_CHECK(m_t >= 1 && m_t <= std::numeric_limits<uint32_t>::max(),
"Invalid Argon2 t parameter");
28 size_t salt_len)
const {
29 argon2(output, output_len, password, password_len, salt, salt_len,
nullptr, 0,
nullptr, 0);
41 size_t key_len)
const {
42 argon2(output, output_len, password, password_len, salt, salt_len, key, key_len, ad, ad_len);
47std::string argon2_family_name(uint8_t f) {
63 return fmt(
"{}({},{},{})", argon2_family_name(m_family), m_M, m_t, m_p);
67 if(m_family != 0 && m_family != 1 && m_family != 2) {
73 return argon2_family_name(m_family);
77 std::chrono::milliseconds msec,
79 std::chrono::milliseconds tune_time)
const {
80 const size_t max_kib = (max_memory == 0) ? 256 * 1024 : max_memory * 1024;
84 const size_t tune_M = (msec >= std::chrono::milliseconds(200) ? 128 : 36) * 1024;
88 Timer timer(
"Argon2");
93 uint8_t output[64] = {0};
94 pwhash->derive_key(output,
sizeof(output),
"test", 4,
nullptr, 0);
103 const uint64_t measured_time = timer.
value() / (timer.
events() * (tune_M / M));
105 const uint64_t target_nsec = msec.count() *
static_cast<uint64_t
>(1000000);
117 uint64_t est_nsec = measured_time;
119 if(est_nsec < target_nsec && M < max_kib) {
120 const uint64_t desired_cost_increase = (target_nsec + est_nsec - 1) / est_nsec;
121 const uint64_t mem_headroom = max_kib / M;
123 const uint64_t M_mult = std::min(desired_cost_increase, mem_headroom);
124 M *=
static_cast<size_t>(M_mult);
128 if(est_nsec < target_nsec / 2) {
129 const uint64_t desired_cost_increase = (target_nsec + est_nsec - 1) / est_nsec;
130 t *=
static_cast<size_t>(desired_cost_increase);
146 const size_t M = iter;
153 return std::make_unique<Argon2>(m_family, M, t, p);
#define BOTAN_ARG_CHECK(expr, msg)
std::unique_ptr< PasswordHash > from_params(size_t M, size_t t, size_t p) const override
std::string name() const override
Argon2_Family(uint8_t family)
std::unique_ptr< PasswordHash > tune(size_t output_length, std::chrono::milliseconds msec, size_t max_memory, std::chrono::milliseconds tune_msec) const override
std::unique_ptr< PasswordHash > default_params() const override
std::unique_ptr< PasswordHash > from_iterations(size_t iter) const override
void derive_key(uint8_t out[], size_t out_len, const char *password, size_t password_len, const uint8_t salt[], size_t salt_len) const override
std::string to_string() const override
Argon2(uint8_t family, size_t M, size_t t, size_t p)
void run_until_elapsed(std::chrono::milliseconds msec, F f)
std::string fmt(std::string_view format, const T &... args)