Created
October 9, 2025 22:02
-
-
Save kuc-arc-f/bb4cb0d4f2a3fdc14319277c262309a5 to your computer and use it in GitHub Desktop.
Rust , hash verify password , example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[package] | |
name = "hello" | |
version = "0.1.0" | |
edition = "2024" | |
[dependencies] | |
anyhow = "1.0.100" | |
argon2 = "0.4" # Argon2 実装(PHC 文字列サポート) | |
rand_core = "0.6" # Salt 生成に OsRng を使うため | |
password-hash = { version = "0.5.0", features = ["getrandom"] } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use anyhow::{ensure, Context, Result}; | |
use argon2::{Argon2, PasswordHasher, PasswordVerifier}; | |
use argon2::password_hash::{SaltString, PasswordHash, rand_core::OsRng}; | |
use std::error::Error; | |
/// パスワードをハッシュ化して PHC 文字列を返す(DB にこの文字列を保存) | |
fn hash_password(password: &str) -> anyhow::Result<String, String> { | |
let argon2 = Argon2::default(); | |
// ランダムソルト生成 | |
let salt = SaltString::generate(&mut OsRng); | |
// ハッシュを生成して PHC 形式の文字列にする(例: $argon2id$v=19$m=4096,t=3,p=1$...) | |
let password_hash = argon2.hash_password(password.as_bytes(), &salt) | |
.expect("error , hash_password"); | |
Ok(password_hash.to_string()) | |
} | |
/// 入力パスワードが保存されたハッシュ(PHC 文字列)と一致するか検証 | |
fn verify_password(password: &str, stored_phc: &str) -> anyhow::Result<bool, String> | |
{ | |
let argon2 = Argon2::default(); | |
let parsed_hash = PasswordHash::new(stored_phc).expect("error , PasswordHash::new2);"); | |
match argon2.verify_password(password.as_bytes(), &parsed_hash) { | |
Ok(()) => Ok(true), | |
Err(argon2::password_hash::Error::Password) => Ok(false), // パスワード不一致 | |
Err(e) => Err("error, argon2.verify_password".to_string()), // その他エラー | |
} | |
} | |
/** | |
* | |
* @param | |
* | |
* @return | |
*/ | |
fn main() -> anyhow::Result<(), String> { | |
let pw = "correct-horse-battery-staple"; | |
// 登録時 | |
let phc = hash_password(pw).expect("error , hash_password"); | |
println!("store this in DB: {}", phc); | |
// ログイン時 | |
// 暗号前、 前回登録した暗号化PS | |
let ok = verify_password(pw, &phc).expect("error , veryfy password"); | |
println!("password ok? {}", ok); | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment