Hashing a string with Sha256

前端 未结 7 1974
一向
一向 2020-12-02 04:31

I try to hash a string using SHA256, I\'m using the following code:

using System;
using System.Security.Cryptography;
using System.Text;
 public class Hash
          


        
相关标签:
7条回答
  • 2020-12-02 05:12

    I also had this problem with another style of implementation but I forgot where I got it since it was 2 years ago.

    static string sha256(string randomString)
    {
        var crypt = new SHA256Managed();
        string hash = String.Empty;
        byte[] crypto = crypt.ComputeHash(Encoding.ASCII.GetBytes(randomString));
        foreach (byte theByte in crypto)
        {
            hash += theByte.ToString("x2");
        }
        return hash;
    }
    

    When I input something like abcdefghi2013 for some reason it gives different results and results in errors in my login module. Then I tried modifying the code the same way as suggested by Quuxplusone and changed the encoding from ASCII to UTF8 then it finally worked!

    static string sha256(string randomString)
    {
        var crypt = new System.Security.Cryptography.SHA256Managed();
        var hash = new System.Text.StringBuilder();
        byte[] crypto = crypt.ComputeHash(Encoding.UTF8.GetBytes(randomString));
        foreach (byte theByte in crypto)
        {
            hash.Append(theByte.ToString("x2"));
        }
        return hash.ToString();
    }
    

    Thanks again Quuxplusone for the wonderful and detailed answer! :)

    0 讨论(0)
提交回复
热议问题