生成密码哈希 [英] Generate password hash

查看:76
本文介绍了生成密码哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的登录系统,我希望对数据库中的密码进行哈希处理.因此,我决定我将继续阅读有关散列以及如何进行散列的知识,但不幸的是,由于我找不到想要的示例,所以这对我来说真的没有任何意义.

For my login system, I wish to hash the passwords in my database. So I decided I would read up on hashing and how to do it but unfortunately it doesn't really make any sense to me as I can't find examples for what I want.

我想要这样,以便在创建用户帐户时,密码会被散列并存储在我的数据库中,然后当他们登录时,它会对登录密码进行散列并使用数据库中的散列密码进行检查.如果可以的话,我将不胜感激.

I want it so that when a user account is created, the password is hashed and stored within my database and then when they login it hashes the login password and checks it with the hashed password in the database. If this makes any sense I'd appreciate the help.

如果您需要我的代码示例或其他示例,请询问,然后将其编辑为我的问题.

If you need examples of my code or whatever then ask and I will edit it into my question.

推荐答案

您可以使用哈希算法,例如 MD5 SHA1 SHA265 SHA512 ,...对密码进行哈希处理.例如:

You can use a hash algorithm like MD5, SHA1, SHA265, SHA512, ... to hash the password. For example:

public string Hash(string password)
{
    var bytes = new UTF8Encoding().GetBytes(password);
    var hashBytes = System.Security.Cryptography.MD5.Create().ComputeHash(bytes);
    return Convert.ToBase64String(hashBytes);
}

然后将密码的哈希存储在数据库中,当您想将输入的密码与数据库存储的值进行比较时,请将输入的值与数据库值进行比较.

Then store the hash of password in database and when you want to compare entered password with database stored value, compare hash of entered value with database value.

编辑

考虑使用 SHA256 MD5 :

Consider using the SHA256 or the SHA512 instead of the MD5:

public string Hash(string password)
{
    var bytes = new UTF8Encoding().GetBytes(password);
    byte[] hashBytes;
    using (var algorithm = new System.Security.Cryptography.SHA512Managed())
    {
        hashBytes = algorithm.ComputeHash(bytes);
    }
    return Convert.ToBase64String(hashBytes);
}

这只是一个简单的示例:在现实世界中,您还应该对哈希使用 salt .您可以在此处了解更多信息.

This is a just simple example: in a real-world scenario, you should use a salt for the hash as well. You can read more about salting here.

这篇关于生成密码哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆