Module dryoc::pwhash

source ·
Expand description

Password hashing functions

PwHash implements libsodium’s password hashing functions, based on Argon2.

Argon2 provides a configurable memory-hard arbitrary-length hashing function that is well suited for password hashing. You may tune the function according to your preferences to either provide stronger collision resistance, or shorter computation times.

You should use PwHash when you want to:

  • authenticate with passwords, and store their salted hashes in a database
  • derive secret keys based on passphrases
  • hash arbitrary data in a manner that’s strongly resistant to collisions

If the serde feature is enabled, the serde::Deserialize and serde::Serialize traits will be implemented for PwHash.

Rustaceous API example

use dryoc::pwhash::*;

// A strong passphrase
let password = b"But, for my own part, it was Greek to me.";

// Hash the password, generating a random salt
let pwhash = PwHash::hash_with_defaults(password).expect("unable to hash");

pwhash.verify(password).expect("verification failed");
pwhash
    .verify(b"invalid password")
    .expect_err("verification should have failed");

Using a custom config, or your own salt

use dryoc::pwhash::*;

// Generate a random salt
let mut salt = Salt::default();
salt.resize(dryoc::constants::CRYPTO_PWHASH_SALTBYTES, 0);
dryoc::rng::copy_randombytes(&mut salt);

// A strong passphrase
let password = b"What's in a name? That which we call a rose\n
                 By any other word would smell as sweet...";

// With customized configuration parameters, return type must be explicit
let pwhash: VecPwHash = PwHash::hash_with_salt(
    password,
    salt,
    Config::interactive().with_opslimit(1).with_memlimit(8192),
)
.expect("unable to hash password with salt and custom config");

pwhash.verify(password).expect("verification failed");
pwhash
    .verify(b"invalid password")
    .expect_err("verification should have failed");

Deriving a keypair from a passphrase and salt

use dryoc::keypair::StackKeyPair;
use dryoc::pwhash::*;

// Generate a random salt
let mut salt = Salt::default();
salt.resize(dryoc::constants::CRYPTO_PWHASH_SALTBYTES, 0);
dryoc::rng::copy_randombytes(&mut salt);

// Use a strong passphrase
let password = b"Is this a dagger which I see before me, the handle toward my hand?";

let keypair: StackKeyPair = PwHash::derive_keypair(password, salt, Config::interactive())
    .expect("couldn't derive keypair");

// now you can use `keypair` with DryocBox

String-based encoding

See PwHash::to_string() for an example of using the string-based encoding API, compatible with crypto_pwhash_str* functions.

Additional resources

Modules

Structs

Type Aliases