Oh right. I have a blog don’t I?

Yes, I did completely forget with the myriad of happenings among my Life 3.0.

I was going to do a proper update and post something profound… alas Life 3.1 is calling at the moment, so I’ll just leave you with a function I quickly put together to generate checksums.

I don’t know why exactly, but I’ve seen countless examples (in C# mostly) of functions that do checksums only in MD5 or only in SHA1 or only in SHA256. And then only for files or only for some text. Well, here’s one that does all of those as in keeping with the programmer’s motto : “Laziness is a virtue”.

/// <summary>
/// Gets the checksum of a local file or some text.
/// </summary>
/// <param name="source">Path to a file or a string</param>
/// <param name="mode">Checksum in sha1, sha256, sha512 or md5 (default)</param>
/// <param name="isFile">True if file mode or false for text mode</param>
/// <returns>Completed checksum</returns>
public static string GetChecksum(string source, string mode = "md5", bool isFile = false)
	byte[] bytes = {};
	Stream fs;

	if (isFile)
		fs = new BufferedStream(File.OpenRead(source), 120000);
		fs = new MemoryStream(Encoding.UTF8.GetBytes(source));

	switch (mode.ToLower())
		case "sha1":
			using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider())
				bytes = sha1.ComputeHash(fs);

		case "sha256":
			using (SHA256CryptoServiceProvider sha256 = new SHA256CryptoServiceProvider())
				bytes = sha256.ComputeHash(fs);

		case "sha512":
			using (SHA512CryptoServiceProvider sha512 = new SHA512CryptoServiceProvider())
				bytes = sha512.ComputeHash(fs);

		case "md5":
			using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
				bytes = md5.ComputeHash(fs);

	// Cleanup
	fs = null;

	return BitConverter
		.Replace("-", "")

2 thoughts on “Oh right. I have a blog don’t I?

    • Oh my. It’s good to know that someone is still looking at this thing ;)

      Honestly between work, life and work, it’s as if I’ve been on autopilot for the last few months. I have some vacation time coming up and I plan to do as little as possible besides, breathing, eating, sleeping and pooping… In no particular order :P

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s