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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16999361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:18:50  来源:igfitidea点击:

Obtain SHA-256 string of a string

c#stringhashsha256

提问by Dariush Jafari

I have some stringand I want to hashit with the SHA-256hash function using C#. I want something like this:

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

 string hashString = sha256_hash("samplestring");

Is there something built into the framework to do this?

框架中是否有内置的东西来做到这一点?

采纳答案by Dmitry Bychenko

The implementation could be like that

实现可能是这样的

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

Edit:Linqimplementation is more concise, but, probably, less readable:

编辑: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")));
  }
} 

Edit 2:.NET Core

编辑 2:.NET 核心

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

回答by aaronsteers

I was looking for an in-line solution, and was able to compile the below from Dmitry's answer:

我正在寻找一个在线解决方案,并且能够从 Dmitry 的回答中编译以下内容:

public static String sha256_hash(string value)
{
    return (System.Security.Cryptography.SHA256.Create()
            .ComputeHash(Encoding.UTF8.GetBytes(value))
            .Select(item => item.ToString("x2")));
}