Learn How to compute SHA256 Hash in C#. Hashing (also known as hash functions) in cryptography is a process of mapping a binary string of an arbitrary length to a small binary string of a fixed length, known as a hash value, a hash code, or a hash. Hash functions are a common way to protect secure sensitive data such as passwords and digital signatures. Some of the modern commonly-used hash functions are MD5, RIPEMD160, SHA1, SHA256, SHA384, and SHA512.
The ComputeHash method of HashAlgorithm computes a hash. It takes a byte array or stream as an input and returns a hash in the form of a byte array of 256 bits.
byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData));
No matter how big the input data is, the hash will always be 256 chars. The following code snippet is an example of how to create a hash of a string.
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();
}
}
Recent Comments