Dar*_*ari 37 c# string hash sha256
我有一些string,我想用使用C#的SHA-256哈希函数来哈希它.我想要这样的东西:
string hashString = sha256_hash("samplestring");
Run Code Online (Sandbox Code Playgroud)
框架中是否有内置功能可以执行此操作?
Dmi*_*nko 103
实施可能就是这样
public static String sha256_hash(String value) {
StringBuilder Sb = new StringBuilder();
using (SHA256 hash = SHA256Managed.Create()) {
Encoding enc = Encoding.UTF8;
Byte[] result = hash.ComputeHash(enc.GetBytes(value));
foreach (Byte b in result)
Sb.Append(b.ToString("x2"));
}
return Sb.ToString();
}
Run Code Online (Sandbox Code Playgroud)
编辑: Linq实现更简洁,但可能不太可读:
public static String sha256_hash(String value) {
using (SHA256 hash = SHA256Managed.Create()) {
return String.Concat(hash
.ComputeHash(Encoding.UTF8.GetBytes(value))
.Select(item => item.ToString("x2")));
}
}
Run Code Online (Sandbox Code Playgroud)
编辑2: .NET Core
public static String sha256_hash(string value)
{
StringBuilder Sb = new StringBuilder();
using (var hash = SHA256.Create())
{
Encoding enc = Encoding.UTF8;
Byte[] result = hash.ComputeHash(enc.GetBytes(value));
foreach (Byte b in result)
Sb.Append(b.ToString("x2"));
}
return Sb.ToString();
}
Run Code Online (Sandbox Code Playgroud)
小智 20
从 .NET 5 开始,您可以使用新Convert.ToHexString方法将哈希字节数组转换为(十六进制)字符串,而无需使用 orStringBuilder等.ToString("X0"):
public static string HashWithSHA256(string value)
{
using var hash = SHA256.Create();
var byteArray = hash.ComputeHash(Encoding.UTF8.GetBytes(value));
return Convert.ToHexString(byteArray);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
58964 次 |
| 最近记录: |