Friday 26 September 2014

MD5 Hash algorithm



I came to know about a very interesting algorithm MD5 Hash algorithm which is very interesting and would like to share the same with you.

While developing visualforce pages we sometime append the Id to url and use that Id in our controller to fetch the information related to that Id, but what will you do if someone change that Id parameter??

For example I have created a two custom object record and there Id appears for first record as " a0B9000000SFvWK "  and for another " a0B9000000SFvWe ". You will see the Id look similar except last character.

Let us suppose my url for visualforce page looks like :   /apex/customPage?Id=a0B9000000SFvWK
and if I change my url Id parameter from " a0B9000000SFvWK " to " a0B9000000SFvWe " then I can see the content from another record which is not good .

To handle such scenario I use MD5 algorithm.

MD5 stands for Message Digest algorithm 5 which is a cryptographic hash function that was invented by Ronald Rivest . MD5 has been utilized in a wide variety of cryptographic applications, and is also commonly used to verify data integrity. 
          The idea behind this algorithm is to take up a random data (text or binary) as an input and generate a fixed size “hash value” as the output. The input data can be of any size or length, but the output “hash value” size is always fixed. Whatever the input size you give, the algorithm generates a fixed size (32 digit hex) MD5 hash.

To deal with the above mentioned scenario I have created a new fields which will store the cryptographic hash value which I get populated using the record Id in after insert trigger and use that cryptographic hash parameter instead of record Id, so now anyone who tries to change the url parameter Id will never able to see other record detail .

this is just a small use of MD5 algorithm .
you can try it same if want using below statement in your developer console

String md5Code = EncodingUtil.convertToHex(Crypto.generateDigest('MD5', Blob.valueOf( INPUT STRING ) ));
 

system.debug(md5Code);


How would you use MD5 ????

Reference : Wiki

No comments:

Post a Comment