Calculating Hashes

Showcasing how to calculate hashes in Java, C# and Ruby!

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 to calculate hashes is the most concise & simple.

comments powered by Disqus