how to salt a password in rust

To salt a password in Rust, you can use the bcrypt crate which provides a way to hash passwords with a salt included. Here is an example code:

main.rs
use bcrypt::{hash, verify, DEFAULT_COST};

fn hash_password(password: &str) -> String {
    let salt = bcrypt::gen_salt(DEFAULT_COST).unwrap();
    let hashed_password = hash(password, &salt).unwrap();
    return hashed_password;
}
232 chars
8 lines

In this example, we use the gen_salt function from bcrypt to generate a random salt with a default cost of 12. Then, we use the hash function to hash the password with the salt. The salt is included in the hashed password, so we only need to store the hashed password in the database.

To verify a password later, we can use the verify function which checks whether a given password matches a given hashed password:

main.rs
fn verify_password(password: &str, hashed_password: &str) -> bool {
    return verify(password, hashed_password).unwrap();
}
125 chars
4 lines

In this example, we use the verify function with the user-supplied password and the stored hashed password. If the function returns true, the password is correct. Otherwise, it's incorrect.

gistlibby LogSnag