Overview
This implementation generates a fixed-length hash value (message digest) from any string or data using the SHA256 algorithm. Hash values are used for detecting data tampering or verifying data identity. A key characteristic is that even a 1-bit difference in the original data results in a completely different output. This guide uses the recommended Create() factory method for modern .NET environments.
Specifications (Input/Output)
- Input: Any string (assumes UTF-8 encoding).
- Output: Base64 string representation of the hash value.
- Characteristics: The same input always produces the same output, but the input cannot be recovered from the output (irreversibility).
Basic Usage
using System.Security.Cryptography;
using System.Text;
var data = Encoding.UTF8.GetBytes("Check Integrity");
// Create algorithm instance
using var sha256 = SHA256.Create();
// Calculate hash
byte[] hashBytes = sha256.ComputeHash(data);
// Convert to string (Base64)
var result = Convert.ToBase64String(hashBytes);
Full Code Example
This is a complete code example that can be run as a console application.
using System;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main()
{
// 1. Data to be hashed
string sourceText = "Security is essential.";
Console.WriteLine($"[Source] {sourceText}");
// 2. Convert to byte array
// UTF-8 is commonly used for web and database storage
byte[] sourceBytes = Encoding.UTF8.GetBytes(sourceText);
// 3. Create hash algorithm
// Using "SHA256.Create()" is recommended over "new SHA256Managed()".
// This automatically selects the best implementation for the OS (e.g., FIPS compliance).
using var algorithm = SHA256.Create();
// 4. Calculate hash value
// The return value is always a 32-byte (256-bit) array
byte[] hashValue = algorithm.ComputeHash(sourceBytes);
// 5. Display results
// Display in Base64 format (concise representation)
Console.WriteLine($"[Hash (Base64)] {Convert.ToBase64String(hashValue)}");
// Display in hexadecimal format (common representation using BitConverter)
string hexString = BitConverter.ToString(hashValue).Replace("-", "").ToLower();
Console.WriteLine($"[Hash (Hex)] {hexString}");
}
}
Customization Points
- Changing Algorithms: To use faster
MD5(not recommended for security) or strongerSHA512, simply replaceSHA256.Create()withMD5.Create()orSHA512.Create(). - Output Format: Choose either
Convert.ToBase64String(Base64) orBitConverter(Hexadecimal) depending on your system requirements. - Encoding: Use
Encoding.Unicode.GetBytesif you are using UTF-16 (standard for internal Windows app data). Since the hash value depends on the input byte sequence, changing the encoding will change the result.
Important Notes
- Do Not Use for Password Storage: This simple hash calculation (without salt or stretching) must not be used for storing passwords. It is vulnerable to rainbow table attacks. For password storage, use dedicated algorithms like
Rfc2898DeriveBytes(PBKDF2) orArgon2. - Avoid SHA256Managed: The
new SHA256Managed()constructor seen in older code may be deprecated in newer .NET versions. Always use the staticSHA256.Create()method. - Collision Resistance: While SHA256 is considered effectively free of collisions (where different data produces the same hash), MD5 and SHA1 are no longer considered secure. Always use SHA256 or higher for security-sensitive tasks.
Advanced Usage
Calculating File Hash Values
This method calculates a hash directly from a stream without loading the entire file into memory, making it safe for large files.
using System.IO;
using System.Security.Cryptography;
string filePath = "example.bin";
using var fileStream = File.OpenRead(filePath);
using var sha256 = SHA256.Create();
// By passing the stream, memory usage remains low even for large files
byte[] fileHash = sha256.ComputeHash(fileStream);
Console.WriteLine($"File Hash: {BitConverter.ToString(fileHash).Replace("-", "")}");
Conclusion
Calculating data hashes is easily implemented using the SHA256.Create() and ComputeHash methods. When handling strings, pay attention to the consistency of encoding (such as UTF-8). It is important to use the correct tools for the job, such as using specialized libraries for high-security requirements like password storage.
