online hash code can be obtained from this site with SHA256.
https://emn178.github.io/online-tools/sha256.html
The hash code of 1 is "6b86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b"
but if we make the hash code input type of 1 hex, "4bf5122f344554c53bde2ebb8cd2b7e3d1600ad631c385a5d7cce23c7785459a" comes out.
I can do the first one in c# code, but I couldn't find a c# code that can do the second one. Could you help?
static string ComputeSha256Hash(string rawData)
{
// Create a SHA256
using (SHA256 sha256Hash = SHA256.Create())
{
// ComputeHash - returns byte array
byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData));
// Convert byte array to a string
StringBuilder builder = new StringBuilder();
for (int i = 0; i < bytes.Length; i )
{
builder.Append(bytes[i].ToString("x2"));
}
return builder.ToString();
}
}
CodePudding user response:
Please try this, the key is convert hex to bytes.
public static byte[] StringToByteArray(string hex)
{
int len = hex.Length;
//the stackoverflow answer assumes you have even length,
//so I insert a 0 if odd length.
if (len % 2 == 1)
{
hex = hex.Insert(0, "0");
}
return Enumerable.Range(0, len)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
static string ComputeSha256Hash(string rawData)
{
using (SHA256 sha256Hash = SHA256.Create())
{
byte[] bytes = sha256Hash.ComputeHash(StringToByteArray(rawData));
StringBuilder builder = new StringBuilder();
for (int i = 0; i < bytes.Length; i )
{
builder.Append(bytes[i].ToString("x2"));
}
return builder.ToString();
}
}
static void Main(string[] args)
{
string hash = ComputeSha256Hash("1");
Console.WriteLine(hash);
Console.ReadKey();
}