Easyhash: An easy interface to generate md5 and sha1 hash in hexadecimal format

December 31, 2011

Generate hash in hexadecimal format is a common need for most developers. Generally this is an easy task, but like a lot of stuff it’s complicated to do in Java. You need to use the java.security.MessageDigest API and convert the result from bytes to a hexadecimal string.

Unfortunately, even in Groovy there is no easy path. With that in mind I developed a small library to do the work.

Using Java

First, Put the easyhash jar into the classpath and then:

import static com.lazythought.easyhash.HashGenerator.*;

assert "ab07acbb1e496801937adfa772424bf7".equals(md5("foo bar baz"));
assert "c7567e8b39e2428e38bf9c9226ac68de4c67dc39".equals(sha1("foo bar baz"));

Using Groovy

With Groovy you can use the @Grab AST:

// Grab the jar

import static com.lazythought.easyhash.HashGenerator.*

assert 'ab07acbb1e496801937adfa772424bf7' == md5('foo bar baz')
assert 'c7567e8b39e2428e38bf9c9226ac68de4c67dc39' == sha1('foo bar baz')

There is also the HashCategory option:

// Grab the jar

import com.lazythought.easyhash.HashCategory

use(HashCategory) {
    assert 'b071ed8a2de56ecd5958305641a81755' == 'frodo bags'.md5()
    assert 'b6b5ece040fd0c467cb189a284c6e7c752c747f5' == 'frodo bags'.sha1()

Dive in

It’s Available at Maven Central.


Source code https://github.com/poiati/easyhash.

comments powered by Disqus