繁体   English   中英

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

[英]How to validate username and password from text file? | Winforms C#

首先,我制作了 textbox1(for username) 、 textbox2(for password) 和 button1(check)。 后:

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 中添加的文本)和第二行的密码。

对不起,我的英语不好。

你可以尝试这样的事情:

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("-", "");
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM