ColdFusion HMACMD5 function

Several months ago, we were integrating our LinkShare affiliate program with our ColdFusion based e-commerce system. During that process, while preparing an MD5 encrypted HMAC message signature for transmitting transaction data to our affiliate tracking account, we encountered a problem with the included encryption algorithms in CF8.

Even though the enterprise version of CF8 includes the hmacmd5 encryption library, we couldn't get it to work, so we reverted to a Java-based implementation wrapped in a function inside one of our Utils CFC's.

Here's how we did it

HMAC MD5 Encryption Function

Place this function inside a Utilities CFC or similar, or use as an UDF


<cffunction name="HMACMD5" returntype="string" access="public" hint="Returns an MD5 encrypted message">
        <!--- You may choose the format of your output --->
<cfargument name="message" type="String" required="true">
        <cfargument name="key" type="String" required="true">
        <cfargument name="outputFormat" type="string" required="false" default="String" hint="String,base64,uBase64">

        <cfset var myMessageString = arguments.message >
        <cfset var myMessageByteArray = myMessageString.getBytes()>

        <cfset var myKey = arguments.key>
        <cfset var myKeyByteArray = myKey.getBytes()>

        <cfscript>

        key = CreateObject("java","javax.crypto.spec.SecretKeySpec");
        key.init(myKeyByteArray,"HmacMD5");

        hmac = CreateObject("java","javax.crypto.Mac");
        hmac = hmac.getInstance("HmacMd5");
        hmac.init(key);

        hmac.update(myMessageByteArray);

        hmac = hmac.doFinal();

        
</cfscript>
        
        <cfswitch expression="#arguments.outputFormat#">
            <cfcase value="base64">
                <cfreturn tobase64(hmac)>
            </cfcase>
            <cfcase value="ubase64">
                <cfreturn URLEncodedFormat(tobase64(hmac))>
            </cfcase>
            <cfdefaultcase>
                <cfreturn toString(hmac)>
            </cfdefaultcase>
        </cfswitch>

</cffunction>

Related Blog Entries

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
BlogCFC was created by Raymond Camden. This blog is running version 5.9.1.001. Contact Blog Owner
Watch the latest videos on YouTube.com