A user sent me some code he was having trouble with, and in the code I saw a rather verbose and complex block of CFML being used to generate random strings for use with CAPTCHA verifications. So, while replying to his e-mail, I also sent him the RandString() function I use myself. And, as it may be of use others, here it is:













6 thoughts

  1. My approach is pretty similar, but I like to start with a list of chars (so as to exclude ambiguous chars like I, 1, l, etc…)
    here’s a sampling:
    <cfset var captchaChars = "2,3,4,5,6,7,8,9,a,b,d,e,f,g,h,j,n,q,r,t,y,A,B,C,D,E,F,G,H,K,L,M,N,P,Q,R,T,U,V,W,X,Y,Z" />
    <cfset var cLength = 2 />
    <cfset var cString="" />
    <cfset var cStringHashed = "" />
    <cfset var i = "" />
    <!— Create a loop that builds the string from the random characters. —>
    <cfloop from="1" to="#cLength#" index="i">
    <cfset cString = cString & listGetAt(captchaChars, RandRange(1, listLen(captchaChars))) />
    </cfloop>
    <cfset cStringHashed = Hash(ucase(cString)) />

  2. I think Ben’s version is great for captchas in the sense that it provides only upper case letters. I do have a slight mod/suggestions to offer. Instead of making length required, make it optional and set the default to a random length. That way, if you do use it for captchas, they’ll constaly vary in length. See below.
    <cffunction name="RandString" output="no" returntype="string">
    <cfargument name="length" type="numeric" required="no">
    <!— Local vars —>
    <cfset var result="">
    <cfset var i=0>
    <!— set a default length —>
    <cfparam name="arguments.length" default="#RandRange(5,9)#">
    <!— Create string —>
    <cfloop index="i" from="1" to="#ARGUMENTS.length#">
    <!— Random character in range A-Z —>
    <cfset result=result&Chr(RandRange(65, 90))>
    </cfloop>
    <!— Return it —>
    <cfreturn result>
    </cffunction>

  3. Correct me if I’m wrong but, it seems the purpose of captcha is to simply make a form secure against scriptbots (yeah, thats my new term). So then length or randomness seems almost useless. Maybe randomness to keep the programmer from hardcoding it into his scriptbot, but not length or case or alpha/numeric/symbol mix. Yes, I know that less security means an easier target for a crack, but whats the possibility and danger for a blog. Your not securing a CIA database.
    I like Ben’s two character simple captcha, he understands.

Leave a Reply