← Back to list

Rust | How to Use Argon2 To Hash Password & Verify Password

Let’s use argon2 to hash & verify password in Rust.

Mike Code · 2025-09-12 13:10 · 2 claps · 1.3 min read
#rust #argon2
Open on Medium ↗

Rust | How to Use Argon2 To Hash Password & Verify Password

Let’s use argon2 to hash & verify password in Rust.

(**Youtube Video**)

First , we need to add dependencies , in cargo.toml:

[dependencies]
argon2 = {version = "0.5.3" }
rand_core = { version = "0.6", features = ["getrandom"] }

We add argon2and rand_core , we use argon2to hash password, and rand_core to use OsRng .

Second , in main.rs:

use argon2::{password_hash::{rand_core::OsRng, SaltString}, Argon2, PasswordHash, PasswordHasher, PasswordVerifier};

fn main() {
    let password1 = "hello world";

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

    let argon2 = Argon2::default();

    let hash_password = argon2.hash_password(password1.as_bytes(), &salt).unwrap().to_string();

    // println!("hashed password: {}", hash_password);

    let parsed_hash = PasswordHash::new(&hash_password).unwrap();

    // println!("parsed hash: {}", parsed_hash);
    let password2 = "123456";
    match  argon2.verify_password(password1.as_bytes(), &parsed_hash) {
        Ok(_) => println!("Password is correct!"),
        Err(_) => println!("Password is uncorrect!")
    }
}

Hash Password:

In main function ,

1 We create a password1 to bind to a string slice value .

2 We use SaltString::generate(&mut OsRng) to generate a salt for hashing password. To use OsRng , we need to add rand_core crate to our project.

3 We call Argon2::default() to initiate a default argon2 instance.

4 we call argon2.hash_password(password1.as_bytes(), &salt).unwrap().to_string() , to hash password1 , first argument ,we need to convert string slice value password1 to bytes , second argument we pass the salt we generated before. To call hash_password function , we need to import PasswordHasher from argon2 . Then we convert hashed password to string.

Now we just hash a password , and convert it to a string value.

Verify Password:

1 We call PasswordHash::new(&hash_password).unwrap(); to parse hashed password from string in PHC String format . So we can verify it .

2 We call argon2.verify_password , we pass password2 of bytes as first argument , second argument we pass hashed password.

3 We usematchexpression to handle the result , If password is correct , it will return a result of Ok , if password is uncorrect , it will return a result of Err.


메타데이터
post_id
32accb1c83cc
slug
rust-how-to-use-argon2-to-hash-password-32accb1c83cc
url
https://medium.com/@mikecode/rust-how-to-use-argon2-to-hash-password-32accb1c83cc
canonical_url
https://medium.com/@mikecode/rust-how-to-use-argon2-to-hash-password-32accb1c83cc
author_url
https://medium.com/@mikecode
status
ok
fetched_at
2026-07-17 14:20:58