问题
I have designed a signup page in C# and all users have to enter their password then the program will hash the password before saving it on a database with a SHA512 hashing method.
Now, I want to verify entered password on the login page with the saved password on database.
Below code is the method that I used to hash the passwords.
Now how can I verify entered password on login page???
byte[] infos = System.Text.Encoding.ASCII.GetBytes(txtPassword.Text);
infos = new System.Security.Cryptography.SHA512Managed().ComputeHash(infos);
String hash = System.Text.Encoding.ASCII.GetString(infos);
回答1:
The Sha* hash family is not appropriate to store passwords safely, because they are way too fast and can be brute-forced too easily. You should switch to a dedicated password-hash function like BCrypt, Argon2 or PBKDF2, which apply a salt and use key-stretching.
A good BCrypt library is available via Nuget: https://www.nuget.org/packages/BCrypt.Net-Next/
Its usage is very straight foreward:
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
string hashToStoreInDb = BCrypt.HashPassword(password);
// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from existingHashFromDb.
bool isPasswordCorrect = BCrypt.Verify(password, existingHashFromDb);
回答2:
What about writing code like this:
using System;
using System.Text;
using System.Security.Cryptography;
using CodeShare.Cryptography;
namespace CodeShare.Cryptography
{
public static class SHA
{
public static string GenerateSHA512String(string inputString)
{
SHA512 sha512 = SHA512Managed.Create();
byte[] bytes = Encoding.UTF8.GetBytes(inputString);
byte[] hash = sha512.ComputeHash(bytes);
return GetStringFromHash(hash);
}
private static string GetStringFromHash(byte[] hash)
{
StringBuilder result = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
result.Append(hash[i].ToString("X2"));
}
return result.ToString();
}
}
}
Example:
public void UsageExample()
{
Console.WriteLine(SHA.GenerateSHA512String("abc"));
//returns DDAF35A193617ABACC417349AE20413112E6FA4E89A97EA20A9EEEE64B55D39A2192992A274FC1A836BA3C23A3FEEBBD454D4423643CE80E2A9AC94FA54CA49F
}
来源:https://stackoverflow.com/questions/57110603/verify-sha512-hashed-password-in-c-sharp