Example on how to derive key with argon2 crate

hello, I use aes_gcm to encrypt data, but I would need to use secure key derivation and I heard that argon2 is good for that, could someone give me an example for a 32 byt key?

You can use the argon2 crate, though you'll have to figure out a salt to go with the password

use argon2::{
    password_hash::{rand_core::OsRng, SaltString},
    Argon2, Params, PasswordHasher,
};
use hex::ToHex;

fn main() {
    // Default len is 32 bytes and customizing the params is annoying, so just asserting that the default is what we expect.
    assert_eq!(Params::DEFAULT_OUTPUT_LEN, 32);

    let argon2 = Argon2::default();
    let salt = SaltString::generate(&mut OsRng);

    let hashed = argon2
        .hash_password("a-very-good-password".as_bytes(), &salt)
        .unwrap();

    let data = hashed.hash.unwrap();

    assert_eq!(data.len(), 32);

    println!("{}", data.encode_hex::<String>());
}

what version of argon2 you used for your example?

2023-01-14 19:55 GMT+01:00, Cole via The Rust Programming Language
Forum notifications@rust-lang.discoursemail.com:

0.4.1

Yes it is what i needed thanks. When i will need later change final
data length to 16 is this hard to configure?

2023-01-15 0:52 GMT+01:00, Cole via The Rust Programming Language
Forum notifications@rust-lang.discoursemail.com:

You can use Argon2::new instead of default and customize the Params value you pass.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.