Beste Tweakenaars,
Voordat ik verder ga, zou ik even kort wat informatie door willen geven:
Function: voor het hashen van het wachtwoord
Function: Creating salt
Registration: code for applying the salt to the password and inserting it into the database
Function: Retrieving salt from database
Check: Validating password in C# code from database
Voordat ik verder ga, zou ik even kort wat informatie door willen geven:
- Programmeertaal: C#
- Programma voor het ontwikkelen van apps: Visual Studio Enterprise 2017
- Onderwerp: het beveiligen van wachtwoorden in een database
Function: voor het hashen van het wachtwoord
C#:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| public static string Hash(string value) { // Hashing SHA256 Algorithm using (SHA256CryptoServiceProvider SHA256 = new SHA256CryptoServiceProvider()) { // New Character coding UTF8 UTF8Encoding UTF8 = new UTF8Encoding(); // Calculate Hash Value and Convert String to byte Array data byte[] data = SHA256.ComputeHash(UTF8.GetBytes(value)); // Return SHA256 string into data return Convert.ToBase64String(data); } } |
Function: Creating salt
C#:
1
2
3
4
5
6
7
| public static String CreateSalt(int size) { RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); var saltBytes = new byte[size]; rng.GetNonZeroBytes(saltBytes); return Convert.ToBase64String(saltBytes); } |
Registration: code for applying the salt to the password and inserting it into the database
C#:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| // 1) MySQL-code in C# string public static string sqlQueryNewUser = "INSERT INTO login (user, pass, salt) VALUES(@User, @Pass, @userSalt)"; // 2) Inserting data MySqlCommand cmd = new MySqlCommand(SQL.sqlQueryNewUser, SQLDatabase.Connection()); cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@User", txtRegUser.Text); string userSalt = Hashing.Hash(CreateSalt(10)); cmd.Parameters.AddWithValue("@Pass", Hashing.Hash(pwbRegPass.Password + userSalt)); cmd.Parameters.AddWithValue("@userSalt", userSalt); cmd.ExecuteNonQuery(); |
Function: Retrieving salt from database
C#:
1
2
3
4
5
6
7
8
| // This code is inside a function... string userName = txtUserName.Text.Trim(); string passWord = pwbPassword.Password.Trim(); string saltQuery = $"SELECT salt FROM login WHERE user = '{userName}'"; SQL.sqlDataTable = new DataTable(); SQL.sqlAdapter = new MySqlDataAdapter(saltQuery, SQLDatabase.Connection()); SQL.sqlAdapter.Fill(SQL.sqlDataTable); string userSalt = SQL.sqlDataTable.Rows[0].ItemArray[0].ToString(); |
Check: Validating password in C# code from database
C#:
1
| string sqlQueryLogin = $"SELECT * FROM login WHERE user='{userName}' AND pass='{Hashing.Hash(passWord + userSalt)}'"; |
[ Voor 11% gewijzigd door umask op 13-06-2019 12:28 ]