Rust密码认证库password-auth的使用,提供安全高效的密码哈希与验证功能
Rust密码认证库password-auth的使用,提供安全高效的密码哈希与验证功能
password-auth是一个Rust密码认证库,提供安全高效的密码哈希与验证功能。它支持多种哈希算法,包括Argon2、PBKDF2等,适合用于用户密码存储和验证。
安装
在项目目录中运行以下Cargo命令:
cargo add password-auth
或者在Cargo.toml中添加:
password-auth = "1.0.0"
使用示例
以下是password-auth的基本用法示例:
use password_auth::{generate_hash, verify_password};
fn main() {
// 用户注册时生成密码哈希
let password = "my_secure_password";
let hash = generate_hash(password);
println!("Generated hash: {}", hash);
// 用户登录时验证密码
let input_password = "my_secure_password";
let is_valid = verify_password(input_password, &hash);
println!("Password is valid: {}", is_valid);
// 错误的密码示例
let wrong_password = "wrong_password";
let is_valid = verify_password(wrong_password, &hash);
println!("Wrong password is valid: {}", is_valid);
}
完整示例
以下是一个更完整的用户认证系统示例,包含用户注册、登录和密码验证功能:
use password_auth::{generate_hash, verify_password};
use std::collections::HashMap;
// 用户结构体,包含用户名和密码哈希
struct User {
username: String,
password_hash: String,
}
impl User {
// 创建新用户并生成密码哈希
fn new(username: &str, password: &str) -> Self {
User {
username: username.to_string(),
password_hash: generate_hash(password),
}
}
// 验证用户密码
fn verify_password(&self, password: &str) -> bool {
verify_password(password, &self.password_hash)
}
}
// 认证系统结构体,管理用户集合
struct AuthSystem {
users: HashMap<String, User>,
}
impl AuthSystem {
// 创建新的认证系统
fn new() -> Self {
AuthSystem {
users: HashMap::new(),
}
}
// 注册新用户
fn register(&mut self, username: &str, password: &str) {
let user = User::new(username, password);
self.users.insert(username.to_string(), user);
}
// 用户登录验证
fn login(&self, username: &str, password: &str) -> bool {
match self.users.get(username) {
Some(user) => user.verify_password(password),
None => false,
}
}
}
fn main() {
let mut auth_system = AuthSystem::new();
// 注册用户
auth_system.register("alice", "alice_password");
auth_system.register("bob", "bob_password");
// 验证登录
println!("Alice login correct: {}", auth_system.login("alice", "alice_password"));
println!("Alice login wrong: {}", auth_system.login("alice", "wrong_password"));
println!("Bob login correct: {}", auth_system.login("bob", "bob_password"));
println!("Non-existent user: {}", auth_system.login("eve", "any_password"));
}
这个库是RustCrypto项目的一部分,采用MIT或Apache-2.0许可证,支持no_std环境,适用于需要密码认证的各种应用场景。
1 回复
Rust密码认证库password-auth使用指南
password-auth
是一个Rust实现的密码认证库,提供了安全高效的密码哈希与验证功能。它基于现代密码学标准,帮助开发者安全地存储和验证用户密码。
主要特性
- 使用Argon2算法(默认)进行密码哈希
- 支持多种哈希算法(Argon2, PBKDF2, Bcrypt)
- 自动盐值生成
- 抗时序攻击的密码验证
- 可配置的计算成本参数
安装
在Cargo.toml
中添加依赖:
[dependencies]
password-auth = "0.4"
基本用法
密码哈希
use password_auth::{generate_hash, VerifyError};
fn main() {
let password = "my_secure_password123";
let hash = generate_hash(password);
println!("Generated hash: {}", hash);
}
密码验证
use password_auth::{verify_password, VerifyError};
fn main() -> Result<(), VerifyError> {
let stored_hash = "$argon2id$v=19$m=65536,t=3,p=4$\
$c29tZXNhbHQ$RdescudvJCsgt3ub+b+dWRWJTmaaJObG";
let input_password = "my_secure_password123";
verify_password(input_password, stored_hash)?;
println!("Password is correct!");
Ok(())
}
高级配置
自定义哈希参数
use password_auth::{generate_hash_with_config, HashConfig, Algorithm};
fn main() {
let config = HashConfig {
algorithm: Algorithm::Argon2id,
time_cost: 4, // 增加迭代次数提高安全性
memory_cost: 65536, // 64MB内存使用
parallelism: 2, // 并行度
};
let password = "my_secure_password123";
let hash = generate_hash_with_config(password, config);
println!("Custom hash: {}", hash);
}
使用不同算法
use password_auth::{generate_hash_with_config, HashConfig, Algorithm};
fn main() {
// 使用PBKDF2算法
let pbkdf2_config = HashConfig {
algorithm: Algorithm::Pbkdf2Sha256,
time_cost: 100_000, // PBKDF2的迭代次数
..Default::default()
};
let hash = generate_hash_with_config("password", pbkdf2_config);
println!("PBKDF2 hash: {}", hash);
}
完整示例代码
下面是一个完整的用户注册和登录验证示例:
use password_auth::{generate_hash, verify_password, VerifyError, HashConfig, Algorithm};
use std::collections::HashMap;
// 模拟用户数据库
struct UserDatabase {
users: HashMap<String, String>, // 用户名 -> 密码哈希
}
impl UserDatabase {
fn new() -> Self {
Self {
users: HashMap::new(),
}
}
// 用户注册
fn register(&mut self, username: &str, password: &str) -> Result<(), String> {
if self.users.contains_key(username) {
return Err("Username already exists".to_string());
}
// 使用默认配置生成密码哈希
let hash = generate_hash(password);
self.users.insert(username.to_string(), hash);
Ok(())
}
// 用户登录验证
fn login(&self, username: &str, password: &str) -> Result<(), String> {
match self.users.get(username) {
Some(hash) => {
match verify_password(password, hash) {
Ok(_) => Ok(()),
Err(VerifyError::IncorrectPassword) => Err("Incorrect password".to_string()),
Err(e) => Err(format!("Verification error: {:?}", e)),
}
}
None => Err("User not found".to_string()),
}
}
// 使用自定义配置注册用户
fn register_with_config(
&mut self,
username: &str,
password: &str,
config: HashConfig,
) -> Result<(), String> {
if self.users.contains_key(username) {
return Err("Username already exists".to_string());
}
// 使用自定义配置生成密码哈希
let hash = generate_hash_with_config(password, config);
self.users.insert(username.to_string(), hash);
Ok(())
}
}
fn main() {
let mut db = UserDatabase::new();
// 注册新用户
if let Err(e) = db.register("alice", "Alice123!") {
println!("Registration failed: {}", e);
return;
}
// 登录测试 - 正确密码
match db.login("alice", "Alice123!") {
Ok(_) => println!("Login successful!"),
Err(e) => println!("Login failed: {}", e),
}
// 登录测试 - 错误密码
match db.login("alice", "wrongpassword") {
Ok(_) => println!("Login successful!"),
Err(e) => println!("Login failed: {}", e),
}
// 使用PBKDF2算法注册用户
let pbkdf2_config = HashConfig {
algorithm: Algorithm::Pbkdf2Sha256,
time_cost: 100_000,
..Default::default()
};
if let Err(e) = db.register_with_config("bob", "Bob456!", pbkdf2_config) {
println!("Registration failed: {}", e);
return;
}
// 验证PBKDF2用户
match db.login("bob", "Bob456!") {
Ok(_) => println!("PBKDF2 login successful!"),
Err(e) => println!("PBKDF2 login failed: {}", e),
}
}
最佳实践
- 始终使用哈希:永远不要以明文存储密码
- 每个用户使用唯一盐值:库已自动处理
- 调整成本参数:根据硬件性能选择适当的安全参数
- 及时更新算法:关注安全公告,必要时迁移到更强算法
错误处理
use password_auth::{verify_password, VerifyError};
fn check_password(input: &str, stored_hash: &str) -> Result<(), String> {
match verify_password(input, stored_hash) {
Ok(_) => Ok(()),
Err(VerifyError::InvalidHashFormat) => Err("Invalid hash format".to_string()),
Err(VerifyError::IncorrectPassword) => Err("Incorrect password".to_string()),
Err(e) => Err(format!("Unexpected error: {:?}", e)),
}
}
password-auth
库为Rust开发者提供了简单易用且安全的密码处理方案,遵循了当前密码存储的最佳实践,是处理用户认证时的一个可靠选择。