-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHash.cs
50 lines (41 loc) · 1.43 KB
/
Hash.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace Blockchain
{
public static class Hash
{
private static SHA256 Sha256Hash = SHA256.Create();
public static string GetHash(string input)
{
return GetHash(Encoding.UTF8.GetBytes(input));
}
public static string GetHash(byte[] data_)
{
// Convert the input string to a byte array and compute the hash.
byte[] data = Sha256Hash.ComputeHash(data_);
// Create a new Stringbuilder to collect the bytes
// and create a string.
var sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
public static bool VerifyHash(string input, string hash)
{
// Hash the input.
var hashOfInput = GetHash(input);
// Create a StringComparer an compare the hashes.
StringComparer comparer = StringComparer.OrdinalIgnoreCase;
return comparer.Compare(hashOfInput, hash) == 0;
}
}
}