哈希密码使用MD5或SHA-256 C# [英] Hashing passwords with MD5 or sha-256 C#

查看:303
本文介绍了哈希密码使用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,preferably SHA-256。

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

任何很好的例子?我希望它能够采取从信息字符串密码;然后散列并存储在变量字符串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 (以<一个href=\"http://derekslager.com/blog/posts/2007/10/bcrypt-dotnet-strong-password-hashing-for-dotnet-and-mono.ashx\">.NET实现这里)或 PBKDF2 (以<一个href=\"http://msdn.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes.aspx\">built-in实施)。

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).

下面是一个使用PB​​KDF2一个例子。

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天全站免登陆