PBKDF2 in Rust. How to use?

What the alternative for this python code in Rust lang?

key = Crypto.Protocol.KDF.PBKDF2(my_pass, salt, length, iterations)

Thanks for answer.

The easiest way to get started on things like this is by searching crates.io for "pbkdf2".

This shows us the pbkdf2 crate which has over 7 million downloads and is owned by a respectable group (the RustCrypto organisation on GitHub).

2022-06-22_17-17-48-55

Down the right hand side there is a link to the documentation.

On the front page, the crate shows a full example of how you would use pbkdf2 to hash a password, complete with stuff like imports and an assertion to show how you might verify a key is valid.

Further down the page is a link to the pbkdf2() function. If we click it, we'll see the function's signature.

This means I give the pbkdf2 function a shared reference to my password's bytes and the salt, plus the number of iterations to run for, and finally a mutable reference to the buffer it should store the result in. If you squint a little bit, this is the same as your Python function except the arguments are passed around differently to let the caller control when memory is allocated.

The PRF generic argument tells the algorithm which hashing implementation to use. You might use something like Hmac<Sha256>, where Hmac comes from the hmac crate and Sha256 comes from the sha2 crate.

So in practice, you would write something like this:

use sha2::Sha256;
use hmac::Hmac;

let password = "my super secret password";
let salt = "asdf";
let rounds = 42;
let mut key = [0_u8; 16];

pbkdf2::pbkdf2::<Hmac<Sha256>>(
    password.as_bytes(), 
    salt.as_bytes(), 
    rounds, 
    &mut key,
);
3 Likes