[英]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.