| 1 |
// SPDX-License-Identifier: MPL-2.0 |
| 2 |
// (c) Hare authors <https://harelang.org> |
| 3 |
|
| 4 |
use crypto::argon2; |
| 5 |
|
| 6 |
// Given a password, derive a key. Given the same password, salt, memory, and |
| 7 |
// passes, this function will always produce the same key. This function is |
| 8 |
// designed to derive cryptographic keys from user-provided passwords, or to |
| 9 |
// verify a password for user logins. |
| 10 |
// |
| 11 |
// The user provides a buffer for the key to be written to via the 'dest' |
| 12 |
// parameter. The minimum supported length for this buffer is 4 bytes, and the |
| 13 |
// recommended length is 32 bytes. |
| 14 |
// |
| 15 |
// The salt parameter should be randomly generated, stored alongside the key, |
| 16 |
// and used in subsequent calls to produce the same key. It must be at least 8 |
| 17 |
// bytes, but 16 bytes is recommended. Use [[crypto::random::]] to generate a |
| 18 |
// different salt for each key. |
| 19 |
// |
| 20 |
// The 'mem' and 'passes' functions are provided to tune the behavior of this |
| 21 |
// algorithm. It is designed to be computationally expensive, and you must |
| 22 |
// adjust these figures to suit your hardware and use-case. If you provide a u32 |
| 23 |
// for 'mem', the algorithm will dynamically allocate that many kilobytes of |
| 24 |
// working memory. To allocate this memory yourself, provide a []u64 instead. |
| 25 |
// The number of passes controls the amount of time spent generating the key, |
| 26 |
// higher numbers take longer. |
| 27 |
// |
| 28 |
// To identify ideal values for these parameters, start with 100000 for 'mem' |
| 29 |
// (100 MiB) and 0 for 'passes'. If it takes too long, reduce the amount of |
| 30 |
// memory, and if it does not take long enough, increase the amount of memory. |
| 31 |
// If you have reached the maximum amount of memory you are able to use, |
| 32 |
// increase passes. |
| 33 |
// |
| 34 |
// The current implementation of this function uses argon2id version 1.3 with the |
| 35 |
// provided number of memory blocks, passes equal to passes + 3, and parallelism |
| 36 |
// set to one. |
| 37 |
export fn derivekey( |
| 38 |
dest: []u8, |
| 39 |
salt: []u8, |
| 40 |
password: []u8, |
| 41 |
mem: (u32 | []u64), |
| 42 |
passes: u32, |
| 43 |
) (void | nomem) = { |
| 44 |
const config = argon2::conf { |
| 45 |
mem = mem, |
| 46 |
parallel = 1, |
| 47 |
passes = passes + 3, |
| 48 |
version = argon2::VERSION, |
| 49 |
... |
| 50 |
}; |
| 51 |
return argon2::argon2id(dest, password, salt, &config); |
| 52 |
}; |