June 15th, 2012

...now browsing by day

 

Groovy, well, is just groovy.

Friday, June 15th, 2012

At some point in your programming career, you will probably need to use an MD5 hash. Most likely just to get the hash for a password.

One of the simplest ways is to use groovy. Here is the code. Don’t even need to put it in the download section. Just copy the code to a file and run it.

import java.security.MessageDigest

srcWord = "password"

if (args.length > 0) {
	srcWord = args[0]
}

println "src: " + srcWord
MessageDigest md5Digest;
byte[] digest;

println "\n****************************************\n"

/* MD5 Code */
md5Digest = MessageDigest.getInstance("MD5");
md5Digest.reset();
md5Digest.update(srcWord.getBytes());
digest = md5Digest.digest();

// println "new BigInteger(1,digest).toString(): " + new BigInteger(1,digest).toString()
println "MD5: " + new BigInteger(1,digest).toString(16)
println "MD5/B64: " + digest.encodeBase64().toString()

println "\n****************************************\n"

/* Now do the same thing for SHA-1 */
md5Digest = MessageDigest.getInstance("SHA-1");
md5Digest.reset();
md5Digest.update(srcWord.getBytes());
digest = md5Digest.digest();
// println "src: " + srcWord
// println "new BigInteger(1,digest).toString(): " + new BigInteger(1,digest).toString()
println "SHA-1: " + new BigInteger(1,digest).toString(16)
println "SHA-1/B64: " + digest.encodeBase64().toString()

println "\n****************************************\n"

/* Now do the same thing for SHA-256 */
md5Digest = MessageDigest.getInstance("SHA-256");
md5Digest.reset();
md5Digest.update(srcWord.getBytes());
digest = md5Digest.digest();
// println "src: " + srcWord
// println "new BigInteger(1,digest).toString(): " + new BigInteger(1,digest).toString()
println "SHA-256: " + new BigInteger(1,digest).toString(16)
println "SHA-256/B64: " + digest.encodeBase64().toString()

println "\n****************************************\n"

/* Now do the same thing for SHA-512 */
md5Digest = MessageDigest.getInstance("SHA-512");
md5Digest.reset();
md5Digest.update(srcWord.getBytes());
digest = md5Digest.digest();
// println "src: " + srcWord
// println "new BigInteger(1,digest).toString(): " + new BigInteger(1,digest).toString()
println "SHA-512: " + new BigInteger(1,digest).toString(16)
println "SHA-412/B64: " + digest.encodeBase64().toString()

println "\n****************************************\n"