Encode Content to MD5 Using GROOVY or GRAILS – with Webhook example

12 / Nov / 2010 by Salil 0 comments

Recently I was working on webhooks (which are getting quite popular for sending notifications to other applications using HTTP POST methods). MD5 encoded content is heavily used in webhooks for security concern.

My purpose of writing this blog is neither to explain MD5 nor webhooks. But just to show you –
1. a quicker way in Java/Groovy/Grails – How to encode a String (or Content) using MD5 algorithm.
2. Receive Webhook request (containing MD5 encoded certificate)

// Below is the content (received in http post request body)
String contentRecievedInRequest = "StringcontentneedtobeverifiedbaseduponMD5algorithm"
// Below is your secret key – this is not in request – but something that you and trust-party know only)
String yourSecretKey = "kfkdjfxx8r7kdf"
// Now Mix your secret key with the content received in http post request
String claimedContent = "StringcontentneedtobeverifiedbaseduponMD5algorithmkfkdjfxx8r7kdf"
// following is usually a hexa value – find in the same http-request-header
String certificate = ‘3df5786adfe37430d8a8d72cb9e7fe56c’

Now, what we need to do here is – Encode claimedContent as MD5.

1. Using Groovy/Java
MessageDigest md5 = MessageDigest.getInstance("MD5");
BigInteger hash = new BigInteger(1, md5.digest());
String hashFromContent = hash.toString(16);

2. Using Grails (Single line solution)
String hashFromContent = claimedContent.encodeAsMD5();

Now what ? Just see if encoded content matches with the certificate received in request-header. If it matches that means it’s valid request (not hacked one).
if(hashFromContent == certificate){
println "GOOD REQUEST — Content Verified"
println "BAD REQUEST"

I hope it might help you somewhere.

Salil Kalia
salil [at] intelligrape [dot] com


Leave a Reply

Your email address will not be published. Required fields are marked *