Creating an MD5 hash in C# is straightforward using the built-in cryptography libraries.
✅ Best Practice: Use System.Security.Cryptography.MD5 for string or file hashing.
Example
using System;
using System.Security.Cryptography;
using System.Text;
string ComputeMD5Hash(string input)
{
using (MD5 md5 = MD5.Create())
{
byte[] inputBytes = Encoding.UTF8.GetBytes(input);
byte[] hashBytes = md5.ComputeHash(inputBytes);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
sb.Append(hashBytes[i].ToString("x2"));
}
return sb.ToString();
}
}
Why use MD5.Create()?
Creates a cryptographic service provider that calculates MD5 hashes efficiently.
Alternative: Hash a File (More Common Use Case)
For scenarios where you need to hash the contents of a file:
using System;
using System.IO;
using System.Security.Cryptography;
string ComputeFileMD5(string filePath)
{
using (var md5 = MD5.Create())
using (var stream = File.OpenRead(filePath))
{
byte[] hashBytes = md5.ComputeHash(stream);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
sb.Append(hashBytes[i].ToString("x2"));
}
return sb.ToString();
}
}
Why hash files this way?
Streams the file content directly through the hash algorithm without loading the entire file into memory.
Security Note
⚠️ Caution: MD5 is considered cryptographically broken and unsuitable for security purposes. For security-sensitive applications, use SHA-256 or better:
using (SHA256 sha256 = SHA256.Create())
{
// Use the same pattern as MD5 examples
// Just replace MD5.Create() with SHA256.Create()
}
MD5 is still useful for non-security purposes like checksums and data verification.
Walt is a computer scientist, software engineer, startup founder and previous mentor for a coding bootcamp. He has been creating software for the past 20 years.
Last updated on: