使用 MD5 或 sha-256 C# 散列密码 [英] Hashing passwords with MD5 or sha-256 C#

查看:20
本文介绍了使用 MD5 或 sha-256 C# 散列密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一个应用程序编写注册表,但仍然遇到了 C# 新手的问题.

I'm writing a register form for a application but still having problems with being new to c#.

我希望将密码加密/散列到 md5 或 sha-256,最好是 sha-256.

I am looking to encrypt/hash passwords to md5 or sha-256, preferably sha-256.

有什么好的例子吗?我希望它能够从字符串密码"中获取信息;然后将其散列并存储在变量string hPassword;"中.有什么想法吗?

Any good examples? I want it to be able to take the information from "string password;" and then hash it and store in the variable "string hPassword;". Any ideas?

推荐答案

不要使用简单的哈希,甚至不要使用加盐的哈希.使用某种密钥强化技术,例如 bcrypt(带有 .NET 实现在这里) 或 PBKDF2(带有 内置实现).

Don't use a simple hash, or even a salted hash. Use some sort of key-strengthening technique like bcrypt (with a .NET implementation here) or PBKDF2 (with a built-in implementation).

这是一个使用 PBKDF2 的示例.

Here's an example using PBKDF2.

要从您的密码生成密钥...

To generate a key from your password...

string password = GetPasswordFromUserInput();

// specify that we want to randomly generate a 20-byte salt
using (var deriveBytes = new Rfc2898DeriveBytes(password, 20))
{
    byte[] salt = deriveBytes.Salt;
    byte[] key = deriveBytes.GetBytes(20);  // derive a 20-byte key

    // save salt and key to database
}

然后测试密码是否有效...

And then to test if a password is valid...

string password = GetPasswordFromUserInput();

byte[] salt, key;
// load salt and key from database

using (var deriveBytes = new Rfc2898DeriveBytes(password, salt))
{
    byte[] newKey = deriveBytes.GetBytes(20);  // derive a 20-byte key

    if (!newKey.SequenceEqual(key))
        throw new InvalidOperationException("Password is invalid!");
}

这篇关于使用 MD5 或 sha-256 C# 散列密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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