登录系统核心是验证用户名密码,结合之前的哈希加密和配置文件,实现安全登录。
案例:登录验证系统
public class LoginSystem { // 模拟数据库存储的用户(密码已用SHA256+盐值加密) private static readonly Dictionary<string, (string PasswordHash, string Salt)> _users = new Dictionary<string, (string, string)> { { "admin", ("e8f69d2c7e5d3a1b0f8e9d7c6b5a493876543210f9e8d7c6b5a493876543210", "salt123") }, { "user1", ("a1b2c3d4e5f67890a1b2c3d4e5f67890a1b2c3d4e5f67890a1b2c3d4e5f67890", "salt456") } }; // 生成盐值+哈希密码 private static (string PasswordHash, string Salt) HashPassword(string password) { string salt = RandomHelper.GetRandomString(6); // 6位随机盐值 string saltedPassword = password + salt; string hash = HashHelper.ComputeSHA256(saltedPassword); return (hash, salt); } // 验证用户名密码 public static bool Login(string username, string password) { if (!_users.TryGetValue(username, out var userData)) { Console.WriteLine("用户名不存在!"); return false; } // 拼接输入密码和存储的盐值,计算哈希 string saltedInput = password + userData.Salt; string inputHash = HashHelper.ComputeSHA256(saltedInput); // 对比哈希值 bool isSuccess = inputHash == userData.PasswordHash; if (isSuccess) { Console.WriteLine("登录成功!"); } else { Console.WriteLine("密码错误!"); } return isSuccess; } // 注册新用户(模拟) public static bool Register(string username, string password) { if (_users.ContainsKey(username)) { Console.WriteLine("用户名已存在!"); return false; } var (hash, salt) = HashPassword(password); _users.Add(username, (hash, salt)); Console.WriteLine("注册成功!"); return true; } public static void Main(string[] args) { Console.WriteLine("=== 登录系统 ==="); Console.Write("请选择操作(1-登录,2-注册):"); string choice = Console.ReadLine()?.Trim() ?? ""; switch (choice) { case "1": Console.Write("请输入用户名:"); string username = Console.ReadLine()?.Trim() ?? ""; Console.Write("请输入密码:"); string password = Console.ReadLine()?.Trim() ?? ""; Login(username, password); break; case "2": Console.Write("请输入用户名:"); string newUsername = Console.ReadLine()?.Trim() ?? ""; Console.Write("请输入密码:"); string newPassword = Console.ReadLine()?.Trim() ?? ""; Register(newUsername, newPassword); break; default: Console.WriteLine("无效操作!"); break; } } }
关键:密码不直接存储,而是存储 “密码 + 盐值” 的哈希值,即使数据泄露,攻击者也无法还原原始密码。