Crate pbkdf2

source ·
Expand description

This crate implements the PBKDF2 key derivation function as specified in RFC 2898.

Examples

PBKDF2 is defined in terms of a keyed pseudo-random function (PRF). Most commonly HMAC is used as this PRF. In such cases you can use pbkdf2_hmac and pbkdf2_hmac_array functions. The former accepts a byte slice which gets filled with generated key, while the former returns an array with generated key of requested length.

use hex_literal::hex;
use pbkdf2::{pbkdf2_hmac, pbkdf2_hmac_array};
use sha2::Sha256;

let password = b"password";
let salt = b"salt";
// number of iterations
let n = 600_000;
// Expected value of generated key
let expected = hex!("669cfe52482116fda1aa2cbe409b2f56c8e45637");

let mut key1 = [0u8; 20];
pbkdf2_hmac::<Sha256>(password, salt, n, &mut key1);
assert_eq!(key1, expected);

let key2 = pbkdf2_hmac_array::<Sha256, 20>(password, salt, n);
assert_eq!(key2, expected);

If you want to use a different PRF, then you can use pbkdf2 and pbkdf2_array functions.

This crates also provides the high-level password-hashing API through the Pbkdf2 struct and traits defined in the password-hash crate.

Add the following to your crate’s Cargo.toml to import it:

[dependencies]
pbkdf2 = { version = "0.12", features = ["simple"] }
rand_core = { version = "0.6", features = ["std"] }

The following example demonstrates the high-level password hashing API:

use pbkdf2::{
    password_hash::{
        rand_core::OsRng,
        PasswordHash, PasswordHasher, PasswordVerifier, SaltString
    },
    Pbkdf2
};

let password = b"hunter42"; // Bad password; don't actually use!
let salt = SaltString::generate(&mut OsRng);

// Hash password to PHC string ($pbkdf2-sha256$...)
let password_hash = Pbkdf2.hash_password(password, &salt)?.to_string();

// Verify password against PHC string
let parsed_hash = PasswordHash::new(&password_hash)?;
assert!(Pbkdf2.verify_password(password, &parsed_hash).is_ok());

Re-exports

Structs

Enums

Functions

  • Generic implementation of PBKDF2 algorithm which accepts an arbitrary keyed PRF.
  • A variant of the pbkdf2 function which returns an array instead of filling an input slice.
  • A variant of the pbkdf2 function which uses HMAC for PRF. It’s generic over (eager) hash functions.
  • A variant of the pbkdf2_hmac function which returns an array instead of filling an input slice.