Storing passwords as plain text is dangerous. Instead, you should hash them using a strong, slow hashing algorithm like BCrypt, which includes built-in salting and resistance to brute-force attacks.
Step 1: Install BCrypt NuGet Package
Before using BCrypt, install the BCrypt.Net-Next package:
dotnet add package BCrypt.Net-Next
or via NuGet Package Manager:
Install-Package BCrypt.Net-Next
Step 2: Hash a Password
Use BCrypt.HashPassword() to securely hash a password before storing it:
using BCrypt.Net; string password = "mySecurePassword123"; string hashedPassword = BCrypt.HashPassword(password); Console.WriteLine(hashedPassword); // Output: $2a$12$...
Step 3: Verify a Password
To check a user's login attempt, use BCrypt.Verify():
bool isMatch = BCrypt.Verify("mySecurePassword123", hashedPassword); Console.WriteLine(isMatch); // Output: True
Ensuring proper hashing should be at the top of your list when it comes to building authentication systems.
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.
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.
⚠️ 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.
Register for my free weekly newsletter.