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()>


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

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


        hmac = hmac.doFinal();

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


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 Contact Blog Owner