Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Hashing in C#

Introduction to Hashing

Hashing is a method of converting a given key into another value. A hash function is used to generate the new value according to a mathematical algorithm. Hashing is commonly used in various applications such as data retrieval, data comparison, and digital signatures. It ensures data integrity and is essential in cryptography.

What is a Hash Function?

A hash function takes an input (or 'message') and returns a fixed-size string of bytes. The output is typically a 'digest' that represents the input data. The same input will always produce the same output, but even a small change in the input will produce a significantly different output.

Common Hash Functions

There are several well-known hash functions used in cryptography:

  • MD5
  • SHA-1
  • SHA-256
  • SHA-512

Hashing in C#

In C#, you can use the System.Security.Cryptography namespace to perform hashing. The following example demonstrates how to use the SHA-256 hash function.

Example: SHA-256 Hashing

using System;
using System.Text;
using System.Security.Cryptography;

class Program
{
    static void Main()
    {
        string input = "Hello, World!";
        string hash = ComputeSha256Hash(input);
        Console.WriteLine($"Input: {input}");
        Console.WriteLine($"Hash: {hash}");
    }

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

Output

Input: Hello, World!
Hash: a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e

Conclusion

Hashing is a critical component in ensuring data integrity and security. With C#, you can easily implement hashing functions using the built-in System.Security.Cryptography namespace. This tutorial provided a basic overview and an example of how to use SHA-256 hashing in C#.