Skip to content

How to implement MD5 in Apex

Apex Hash

What is MD5?
The MD5 (message-digest algorithm) hashing algorithm is a one-way cryptographic function that accepts a message of any length as input and returns as output a fixed-length digest value to be used for authenticating the original message.

The MD5 hash function was originally designed for use as a secure cryptographic hash algorithm for authenticating digital signatures. But MD5 has been deprecated for uses other than as a noncryptographic checksum to verify data integrity and detect unintentional data corruption.

What is MD5 used for?
Although originally designed as a cryptographic message authentication code algorithm for use on the internet, MD5 hashing is no longer considered reliable for use as a cryptographic checksum because security experts have demonstrated techniques capable of easily producing MD5 collisions on commercial off-the-shelf computers. An encryption collision means two files have the same hash. Hash functions are used for message security, password security, computer forensics and cryptocurrency.


But for us in Salesforce, there is no harm in using an MD5 hash for simple use cases like data organization.


String key = 'hgdhdhhdjfh12ehsn';
String secret = 'DNf32sdsj747dhkjd8893jjjdjds7jjk';
//Generating current Unix timestamp (in seconds)
String getTime = string.valueOf(Datetime.Now().getTime()/1000); 

String requestInput = key + secret + getTime;

Blob requestBlob = Blob.valueOf(requestInput);
Blob hash = Crypto.generateDigest('MD5', requestBlob);
//Need to convert into hex to generate the equivalent of md5(string) method of PHP.
String requestSignature = EncodingUtil.convertToHex(hash);

http h = new Http();
HttpRequest req = new HttpRequest();
//For security purpose, actual have been replaced with dashes
req.setHeader('Api-Key', key);
req.setHeader('Api-Signature', requestSignature);
HttpResponse res = h.send(req);


For More:

Mid Level Apex Tutorial

Join the conversation

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

error: Content is protected !!