我在尝试获取哈希字符串时遇到问题c#.
我已经尝试了一些网站,但大多数人都使用文件来获取哈希值.其他用于字符串的东西有点复杂.我找到了像这样的Web身份验证示例:
FormsAuthentication.HashPasswordForStoringInConfigFile(tbxPassword.Text.Trim(), "md5")
Run Code Online (Sandbox Code Playgroud)
我需要使用hash来创建一个包含文件名更安全的字符串.我怎样才能做到这一点?
例:
string file = "username";
string hash = ??????(username);
Run Code Online (Sandbox Code Playgroud)
我应该使用其他哈希算法而不是"md5"吗?
Dmi*_*nov 159
using System.Security.Cryptography;
public static byte[] GetHash(string inputString)
{
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();
}
Run Code Online (Sandbox Code Playgroud)
补充说明
and*_*fox 48
获取用于密码存储目的的哈希字符串的最快方法是以下代码:
internal static string GetStringSha256Hash(string text)
{
if (String.IsNullOrEmpty(text))
return String.Empty;
using (var sha = new System.Security.Cryptography.SHA256Managed())
{
byte[] textData = System.Text.Encoding.UTF8.GetBytes(text);
byte[] hash = sha.ComputeHash(textData);
return BitConverter.ToString(hash).Replace("-", String.Empty);
}
}
Run Code Online (Sandbox Code Playgroud)
备注:
sha则应将变量的创建重构为类字段;Ehs*_*edi 13
这里的所有哈希代码示例都已过时。在.NET 5中,为我们提供了一种新的散列数据方法,它速度加倍并且零内存分配。那不是很酷吗?您只需HashData(byte[])在您最喜欢的哈希算法类上使用新的静态即可。
byte[] buffer = Encoding.UTF8.GetBytes(input);
byte[] digest = SHA256.HashData(buffer);
Run Code Online (Sandbox Code Playgroud)
Microsoft在其分析器中有一条新规则,用于检测旧的用法并用新的 API 替换它们。
我真的不明白你问题的全部范围,但是如果你需要的只是字符串的哈希值,那么很容易得到它.
只需使用GetHashCode方法即可.
像这样:
string hash = username.GetHashCode();
Run Code Online (Sandbox Code Playgroud)
我认为你所寻找的不是散列而是加密.使用散列,您将无法从"散列"变量中检索原始文件名.使用加密,您可以,并且它是安全的.
有关.NET加密的更多信息,请参阅ASP.NET中的AES with VB.NET.
| 归档时间: |
|
| 查看次数: |
149277 次 |
| 最近记录: |