获取字符串的SHA-256字符串

我有一些string,我想 哈希值 与它 采用C#哈希函数。我想要这样的东西:

 string hashString = sha256_hash("samplestring");

框架中是否有内置的工具可以做到这一点?

回答:

实现可能是这样的

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();

}

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")));

}

}

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

}

以上是 获取字符串的SHA-256字符串 的全部内容, 来源链接: utcz.com/qa/432191.html

回到顶部