Skip to content

Instantly share code, notes, and snippets.

@thangngoc89
Created June 29, 2021 20:08
Show Gist options
  • Save thangngoc89/6e79bf44597476c5b3874a4fb4b38959 to your computer and use it in GitHub Desktop.
Save thangngoc89/6e79bf44597476c5b3874a4fb4b38959 to your computer and use it in GitHub Desktop.
Dream.as password hashing
module Hash = Argon2.ID;
type error = Argon2.ErrorCodes.t;
type params = {
time_cost: int,
memory_cost_kiB: int,
parallelism: int,
hash_len: int,
salt_len: int,
};
// Recommended parameters
// https://argon2-cffi.readthedocs.io/en/stable/api.html#argon2.PasswordHasher
let recommend_params = {
time_cost: 2,
memory_cost_kiB: 100 * 1024, // 100MiB
parallelism: 8,
hash_len: 16,
salt_len: 16,
};
// Minimum parameters
// https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#argon2id
let minimum_params = {
time_cost: 1,
memory_cost_kiB: 37 * 1024,
parallelism: 1,
hash_len: 16,
salt_len: 16,
};
let hash = (~params=recommend_params, password) => {
let {
time_cost: t_cost,
memory_cost_kiB: m_cost,
parallelism,
hash_len,
salt_len,
} = params;
let salt = Dream.random(16);
let encoded_len =
Argon2.encoded_len(
~t_cost,
~m_cost,
~parallelism,
~salt_len,
~hash_len,
~kind=ID,
);
let encoded =
Hash.hash_encoded(
~t_cost,
~m_cost,
~parallelism,
~pwd=password,
~salt,
~hash_len,
~encoded_len,
);
switch (encoded) {
| Result.Ok(encoded) => Result.Ok(Hash.encoded_to_string(encoded))
| Result.Error(e) => Result.Error(e)
};
};
let verify = (~hash, ~password) => {
Argon2.verify(~encoded=hash, ~pwd=password, ~kind=ID);
};
let error_to_string = Argon2.ErrorCodes.message;
type error;
type params = {
time_cost: int,
memory_cost_kiB: int,
parallelism: int,
hash_len: int,
salt_len: int,
};
let recommend_params: params;
let minimum_params: params;
let hash: (~params: params=?, string) => result(string, error);
let verify: (~hash: string, ~password: string) => result(bool, error);
let error_to_string: error => string;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment