C#中的哈希字符串 [英] Hash string in c#

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

问题描述

c# 中尝试获取哈希字符串时遇到问题.

I have a problem when trying get a hash string in c#.

我已经尝试过一些网站,但大多数都使用文件来获取哈希值.其他用于字符串的有点太复杂了.我找到了像这样的 Windows 身份验证示例:

I already tried a few websites, but most of them are using files to get the hash. Others that are for strings are a bit too complex. I found examples for Windows authentication for web like this:

FormsAuthentication.HashPasswordForStoringInConfigFile(tbxPassword.Text.Trim(), "md5")

我需要使用散列来使包含文件名的字符串更安全.我该怎么做?

I need to use a hash to make a string that contains a filename more secure. How can I do that?

示例:

string file  = "username";
string hash = ??????(username); 

我应该使用其他散列算法而不是md5"吗?

Should I use another hashing algorithm and not "md5"?

推荐答案

using System.Security.Cryptography;

public static byte[] GetHash(string inputString)
{
    using (HashAlgorithm algorithm = SHA256.Create())
        return algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString));
}

public static string GetHashString(string inputString)
{
    StringBuilder sb = new StringBuilder();
    foreach (byte b in GetHash(inputString))
        sb.Append(b.ToString("X2"));

    return sb.ToString();
}

附加说明

  • 由于 MD5 和 SHA1 是过时且不安全的算法,因此此解决方案使用 SHA256.或者,您可以使用 BCryptScrypt 正如评论中指出的那样.
  • 此外,请考虑加盐"您的哈希值并使用经过验证的加密算法,如在评论中指出.
  • Since MD5 and SHA1 are obsolete and insecure algorithms, this solution uses SHA256. Alternatively, you can use BCrypt or Scrypt as pointed out in comments.
  • Also, consider "salting" your hashes and use proven cryptographic algorithms, as pointed out in comments.

这篇关于C#中的哈希字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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