Transformation Thursday - C# to Ruby, How to create a MD5 Hash

August 21, 2014

Earlier this week I revisited some code in our code base that hashes a password. I done some investigation how to do this via C# and Ruby. Let’s firstly remind ourselves where MD5 hashing comes from and what it is.

MD5 was designed by Ron Rivest in 1991 to replace an earlier hash function, MD4. The MD5 message-digest algorithm is a widely used cryptographic hash function producing a 128-bit (16-byte) hash value, typically expressed in text format as a 32 digit hexadecimal number. MD5 has been utilized in a wide variety of cryptographic applications and is also commonly used to verify data integrity.

So you could use an MD5 hash on the contents of a file to check if anything changed on it, or use it to hash a string. You however would want to use something stronger than MD5 if you need to hash and store passwords.

So how do you do this in C#:

So firstly what you don’t see from this code is the two using statements we need.

using System.Text;
using System.Security.Cryptography;

Without those two using statements, the StringBuilder class and MD5 class would just moan. First thing we do is create a new MD5 class using the Create factory method. Next we ensure we get the byte value of the string we are hashing. We can then compute the hash passing in the byte array we get from the string. The next few lines loop over our MD5 hash byte array and converts each item into a lowercase hexadecimal character. Nice from that we have our hash and can do whatever we want.

Next up is the Ruby implementation, are you ready for this? Well, okay here goes:

Bam drops mic

That’s me I am done here.


Discussion, links, and tweets

My name is Deon Heyns and I am a developer learning things and documenting them in realtime. Python, Ruby, Scala, .NET, and Groovy are all languages I have written code in. I appeared in the New York Post once. I host my code up at GitHub and Bitbucket so have a look at my code, fork it and send those pull requests.

comments powered by Disqus