Calculating Hashes

// November 25th, 2010 // Programming

Tags: , , , , , , , , , , ,

In my old blog, 2 of the popular posts were about calculating MD5, SHA-1, SHA-256, SHA-384, SHA-512 hashes in Java and C#, I am still getting a little traffic from diggs of those posts :). So today I decided to post it again, and since I am now a fan of Ruby, i’ll also added that in.

Java :

public String getHash(String message, String algorithm) {
	try {
		byte[] buffer = message.getBytes();
		MessageDigest md = MessageDigest.getInstance(algorithm);
		md.update(buffer);
		byte[] digest = md.digest();
		String hexValue = null;
		for(int i = 0 ; i < digest.length ; i++) {
			int b = digest[i] & 0xff;
			if (Integer.toHexString(b).length() == 1) hex = hex + "0";
			hex  = hex + Integer.toHexString(b);
		}
		return hex;
	} catch(NoSuchAlgorithmException e) {
		e.printStackTrace();
	}
	return null;
}

C# :

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

public String getHash(String message, String algo) {
	byte[] sourceBytes = Encoding.Default.GetBytes(message);
	byte[] hashBytes = null;
	Console.WriteLine(algo);
	switch(algo.Trim().ToUpper()) {
		case "MD5":
			hashBytes = MD5CryptoServiceProvider.Create().ComputeHash(sourceBytes);
			break;
		case "SHA1":
			hashBytes = SHA1Managed.Create().ComputeHash(sourceBytes);
			break;
		case "SHA256":
			hashBytes = SHA256Managed.Create().ComputeHash(sourceBytes);
			break;
		case "SHA384":
			hashBytes = SHA384Managed.Create().ComputeHash(sourceBytes);
			break;
		case "SHA512":
			hashBytes = SHA512Managed.Create().ComputeHash(sourceBytes);
			break;
		default:
			break;
	}
	StringBuilder sb = new StringBuilder();
	for(int i = 0 ; hashBytes != null && i < hashBytes.Length ; i++) {
		sb.AppendFormat("{0:x2}", hashBytes[i]);
	}
	return sb.ToString();
}

Ruby:

require 'digest'

def getHash(message, algo='md5')
  case algo.strip.upcase
  when "MD5" then Digest::MD5.hexdigest(message)
  when "SHA1" then Digest::SHA1.hexdigest(message)
  when "SHA256" then Digest::SHA256.hexdigest(message)
  when "SHA384" then Digest::SHA384.hexdigest(message)
  when "SHA512" then Digest::SHA512.hexdigest(message)
  end
end

As you can see, the Ruby version is the most concise & simple.

VN:F [1.9.13_1145]
Rating: 10.0/10 (1 vote cast)
VN:F [1.9.13_1145]
Rating: 0 (from 0 votes)
Calculating Hashes, 10.0 out of 10 based on 1 rating

Leave a Reply

 

Get Adobe Flash playerPlugin by wpburn.com wordpress themes