如何从文本文件中验证用户名和密码?|Winforms C#

本文关键字:密码 Winforms 用户 文本 文件 验证 | 更新日期: 2024-10-19 18:59:26

首先我制作了textbox1(用于用户名)、textbox2(用于密码)和button1(检查)。之后:

private void button1_Click(object sender, EventArgs e)
{
    FileStream fs = new FileStream(@"D:'C#'test.txt", FileMode.Open, FileAccess.Read, FileShare.None);
    StreamReader sr = new StreamReader(fs);
}

我想检查test.txt第一行的用户名(等于textbox1中我添加的文本)和第二行的密码。

抱歉我英语不好。

如何从文本文件中验证用户名和密码?|Winforms C#

你可以试试这样的东西:

private void button1_Click(object sender, EventArgs e){
     string[] lines = System.IO.File.ReadAllLines(@"D:'C#'test.txt");
     String username = lines[0];
     String password = lines[1];
}

然而,这不是一个很好的方式来存储您的用户名和密码。我想你只是在测试一些东西。

问题的最简单答案是逐行读取文本文件。然而,我强烈建议至少对密码进行种子设定和哈希处理。

这是一个使用种子SHA256散列密码的简短示例。这只是为了展示概念,不应该按原样使用。

    void Test()
    {
        string pwd = "Testing1234";
        string user = "username";
        StorePassword(user, pwd);
        bool result = ValidatePassword(user, pwd);
        if (result == true) Console.WriteLine("Match!!");
    }
    private void StorePassword(string username, string password)
    {
        var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        var random = new Random();
        var salt = new string(
            Enumerable.Repeat(chars, 8)
                   .Select(s => s[random.Next(s.Length)])
                   .ToArray());
        string hash = GetHash(salt + password);
        string saltedHash = salt + ":" + hash;
        string[] credentials = new string[] { username, saltedHash };
        System.IO.File.WriteAllLines(@"D:'C#'test.txt",credentials);
    }
    bool ValidatePassword(string username, string password)
    {
        string[] content = System.IO.File.ReadAllLines(@"D:'C#'test.txt");
        if (username != content[0]) return false; //Wrong username
        string[] saltAndHash = content[1].Split(':'); //The salt will be stored att index 0 and the hash we are testing against will be stored at index 1.
        string hash = GetHash(saltAndHash[0] + password);
        if (hash == saltAndHash[1]) return true;
        else return false;
    }
    string GetHash(string input)
    {
        System.Security.Cryptography.SHA256Managed hasher = new System.Security.Cryptography.SHA256Managed();
        byte[] bytes = hasher.ComputeHash(Encoding.UTF8.GetBytes(input));
        return BitConverter.ToString(bytes).Replace("-", "");
    }