我已经用C#设计了一个注册页面,所有用户都必须输入密码,然后程序将使用SHA512哈希方法将密码保存在数据库上之前对密码进行哈希处理。
现在,我要验证登录页面上输入的密码以及数据库中保存的密码。
下面的代码是我用来哈希密码的方法。
现在如何在登录页面上验证输入的密码?
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);
答案 0 :(得分:0)
如何编写这样的代码:
class Posts(models.Model):
title = models.CharField(max_length=200, blank=True)
body = models.TextField(blank=True)
created_at = models.DateTimeField(default=datetime.datetime.now)
post_image = models.ImageField(upload_to=get_image_path, blank=True, null=True)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
# I would like to use the function beneath to resize my images before I save them to my database
self.post_image.update_dimension_fields(self, instance, force=False, *args, **kwargs)
super().save(*args, **kwargs) # Call the "real" save() method.
class Meta:
verbose_name_plural = "Posts"
示例:
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();
}
}
}
答案 1 :(得分:0)
Sha *哈希家族不适合安全地存储密码,因为它们的速度太快并且容易被暴力破解。您应该切换到专用的密码哈希函数,例如BCrypt,Argon2或PBKDF2,它们会加盐并使用键拉伸。
可以通过Nuget获得良好的BCrypt库:https://www.nuget.org/packages/BCrypt.Net-Next/
它的用法非常直接:
// 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);