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)

[groovy]
// 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’
[/groovy]

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

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

2. Using Grails (Single line solution)
[groovy]
String hashFromContent = claimedContent.encodeAsMD5();
[/groovy]

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).
[groovy]
if(hashFromContent == certificate){
println "GOOD REQUEST — Content Verified"
}else{
println "BAD REQUEST"
}
[/groovy]

I hope it might help you somewhere.

Salil Kalia
salil [at] intelligrape [dot] com

FOUND THIS USEFUL? SHARE IT

Leave a Reply

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