简体   繁体   中英

Creating a Login Screen, WPF, how to store usernames and passwords

For my application, i have a part where all the settings are. This can be accessed by clicking the settings button. Now, what i want to do, i before it pops up the settings, add a small login screen, so that only an admin can change the settings.

At first i thought of keeping it very simple by just add a default username "Admin" and password "AdminPass" This i would just check if the userinput is the same as what it should be in code, and if it is the dame it will continue.

But there is a downside at this, the username and pass are hardcoded inside, so it cant be changed anymore within the application. (unless i would do it in the settings, but that is just a xml that can be read outside the app, and thus not a correct solution).

So i wonder, what would be the best approach for this problem ? So that after logging in the first time with the default, the admin can change the admin pass, and this is saved into the application (and thus is saved after the application restarts).

One way could be to get the hash of password and store in a text file. Then when user enter the password, hash it. Match with the hash stored in the text file. If it matches you can allow login.

Similarly if user decides to change the password, replace the old hash with the new one

You can use this code for hashing the password

public static string EncodePassword(string password)
{  byte[] bytes   = Encoding.Unicode.GetBytes(password);
   byte[] inArray = HashAlgorithm.Create("SHA1").ComputeHash(bytes);
   return Convert.ToBase64String(inArray);
}

You can also save this information in application configuration file

Best solution if possible would be to create a database table for users. This will allow you to change passwords and have multiple user accounts for your application.

If for some reason you don't want to use a database system and we are not talking for a high security application, then an encrypted password could be saved in your xml file in a non reversible encryption such as the MD5.

System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] data = System.Text.Encoding.ASCII.GetBytes(yourPassword);
data = x.ComputeHash(data);
String md5Hash = System.Text.Encoding.ASCII.GetString(data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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