Skip to content

Instantly share code, notes, and snippets.

@bennadel
Created February 27, 2012 14:19
ColdFusion 10 Beta - Generating Hash-Based Message Authentication Codes With Hmac()
<cfscript>
// I take an API key and a content value and generate a hashed-
// message authenticate code using MD5 so as to be able to
// authenticate that the message is from a trusted source.
function md5Digest( content, apiKey ){
// We need to hash the content using the MD5 algorithm. Let's
// define a key specification for the HmacMD5 alrorithm using
// our API key.
var secretKeySpec = createObject( "java", "javax.crypto.spec.SecretKeySpec" ).init(
toBinary( toBase64( apiKey ) ),
javaCast( "string", "HmacMD5" )
);
// Now, let's create our MAC (Message Authentication Code)
// generator to hash the actual email post content.
var mac = createObject( "java", "javax.crypto.Mac" ).getInstance(
javaCast( "string", "HmacMD5" )
);
// Initialize the MAC using our secret key.
mac.init( secretKeySpec );
// Hash the content of the message - returnes byte array.
var hashedBytes = mac.doFinal(
toBinary( toBase64( content ) )
);
// Now that we have our hashed bytes, we need to encode them
// as a Hexadecimal string. Create a buffer to hold the hex
// values as we encode each byte.
var hexBuffer = [];
// Loop over the bytes to encode them individually as HEX.
for (var byte in hashedBytes){
// Get the hex value for this byte. When converting the
// byte, only use the right-most 8 bits - the sign of
// the byte can create oddities otherwise.
var hexValue = formatBaseN( bitAnd( 255, byte ), 16 );
// When appending the HEX value, ensure that the leading
// zero has not been trimmed during the conversion.
arrayAppend(
hexBuffer,
right( "0#hexValue#", 2 )
);
}
// Flatten and return the Hex buffer.
return(
ucase( arrayToList( hexBuffer, "" ) )
);
}
// ------------------------------------------------------ //
// ------------------------------------------------------ //
// Set up our security key and our message to authenticate.
apiKey = "icanhazsecyouritea";
message = "The content to be authenticed using message digest!";
// Get HMAC (hashed-message authentication code) using the manual
// algorithm and hex conversion.
writeOutput(
md5Digest( message, apiKey )
);
writeOutput( "<br />" );
// Use new built-in Hmac() method.
writeOutput(
hmac( message, apiKey, "HmacMD5" )
);
</cfscript>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment