How to MD5 Hash in C#

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.

0
128

Related

When working with SQL Server, you may often need to count the number of unique values in a specific column. This is useful for analyzing data, detecting duplicates, and understanding dataset distributions.

Using COUNT(DISTINCT column_name)

To count the number of unique values in a column, SQL Server provides the COUNT(DISTINCT column_name) function. Here’s a simple example:

SELECT COUNT(DISTINCT column_name) AS distinct_count
FROM table_name;

This query will return the number of unique values in column_name.

Counting Distinct Values Across Multiple Columns

If you need to count distinct combinations of multiple columns, you can use a subquery:

SELECT COUNT(*) AS distinct_count
FROM (SELECT DISTINCT column1, column2 FROM table_name) AS subquery;

This approach ensures that only unique pairs of column1 and column2 are counted.

Why Use COUNT DISTINCT?

  • Helps in identifying unique entries in a dataset.
  • Useful for reporting and analytics.
  • Efficient way to check for duplicates.

By leveraging COUNT(DISTINCT column_name), you can efficiently analyze your database and extract meaningful insights. Happy querying!

0
104

In C#, you can format an integer with commas (thousands separator) using ToString with a format specifier.

int number = 1234567;
string formattedNumber = number.ToString("N0"); // "1,234,567"
Console.WriteLine(formattedNumber);

Explanation:

"N0": The "N" format specifier stands for Number, and "0" means no decimal places. The output depends on the culture settings, so in regions where , is the decimal separator, you might get 1.234.567.

Alternative:

You can also specify culture explicitly if you need a specific format:

using System.Globalization;

int number = 1234567;
string formattedNumber = number.ToString("N0", CultureInfo.InvariantCulture);
Console.WriteLine(formattedNumber); // "1,234,567"
3
224

String interpolation, introduced in C# 6.0, provides a more readable and concise way to format strings compared to traditional concatenation (+) or string.Format(). Instead of manually inserting variables or placeholders, you can use the $ symbol before a string to directly embed expressions inside brackets.

string name = "Walt";
string job = 'Software Engineer';

string message = $"Hello, my name is {name} and I am a {job}";
Console.WriteLine(message);

This would produce the final output of:

Hello, my name is Walt and I am a Software Engineer

String interpolation can also be chained together into a multiline string (@) for even cleaner more concise results:

string name = "Walt";
string html = $@"
    <div>
        <h1>Welcome, {name}!</h1>
    </div>";
36
129