Fun with strings and hashes in ColdFusion
At work we do a bit of web development using ColdFusion and earlier this week I got stumped by a problem which I thought I would share. We are currently working on a RESTful API which requires an API signature similar to how flickr does. When it came to writing my unit tests I created a signature grabbing a private key out of the database to test against. I ran the test and BAM! it failed, now this was half expected it was the first time I’d run the test. So it turned out that the code was syntactically fine, then I thought maybe I had made a mistake in the process of creating a signature.
With that ins mind the next step I took was comparing the raw pre-hashed version of both signatures, to my surprise I found that the test passed. This was beginning to not make sense, it wasn’t until I altered the test to fail that I saw what the issue was: when I retrieved the key from the database all of the characters were uppercase however when coldfusion retrieved the key all of the characters were lower case. After updating the test to use a lower case version of the key it passed successfully.
So it turns out that ColdFusion is not case sensitive when it does string comparisons, but the hash function does care what case the characters are, as you can lead to a frustrating situation. Now I’m not expecting you to take my word for it so I have quickly coded up some example code showing the issue.
<cfset original = "secret-key" /> <cfset upperCase = "SECRET-KEY" /> <cfset match = "secret-key" /> <cfset random = "5q2up0awet530" /> <cfset originalHash = Hash(original) /> <cfset upperCaseHash = Hash(upperCase) /> <cfset matchHash = Hash(match) /> <cfset randomHash = Hash(random) /> <cfoutput> <h1>String Matching</h1> <table border="1" style="width: 30%"> <tr><th></th><th>Upper case</th><th>Match</th><th>Random</th></tr> <tr> <th style="text-align: left">Original</th> <td style="text-align: center">#original eq upperCase#</td> <td style="text-align: center">#original eq match#</td> <td style="text-align: center">#original eq random#</td> </tr> </table> <h1>Hash Matching</h1> <table border="1" style="width: 30%"> <tr><th></th><th>Upper case</th><th>Match</th><th>Random</th></tr> <tr> <th style="text-align: left">Original</th> <td style="text-align: center">#originalHash eq upperCaseHash#</td> <td style="text-align: center">#originalHash eq matchHash#</td> <td style="text-align: center">#originalHash eq randomHash#</td> </tr> </table> </cfoutput>
When you run the code this is the output you should get.
As I found the hard way when ColdFusion says two strings are the same it may not necessarily be true.
Tags: ColdFusion, Programming, Work
Category: Programming |
Comment



HTML
CSS