I need a way to generate "keys" for users to access a webservice API, or some other secured resource, that is more user-friendly than a UUID.
By utilizing ColdFusion's Java foundation we can generate a psudo-random set of digits that are more palpable to our average user base.
The objective here is to create a function that we can use to generate a fixed-length psudo-random set of digits to use a key to give to users. We will make that length definable for better flexibility.
The first order of business is to define what characters will make up our random key. For this function we are creating we will use the alphabet and numbers.
< cfset var chars = "abcdefghijklmnopqrstuvwxyz1234567890" />
From here we will initialize Java's Random class to generate random numbers for us. We will use this while creating our digits to determine the index into the chars string to pull characters from. We will also initialize a StringBuffer for faster string creation. Once we have what we need, we will loop and append a series of random digits until we have reached the specified length. Let's take a look.
<
cfcomponent
name
=
"RandomId"
>
<
cffunction
name
=
"generate" returntype
=
"string"
access
=
"public" output
=
"false"
>
<
cfargument
name
=
"numCharacters"
type
=
"numeric"
required
=
"false"
default
=
"8"
/>
<
cfset
var chars
=
"abcdefghijklmnopqrstuvwxyz1234567890"
/>
<
cfset
var random
=
createObject
(
"java",
"java.util.Random"
).init
(
)
/>
<
cfset
var result
=
createObject
(
"java",
"java.lang.StringBuffer"
).init
(
javaCast
(
"int",
arguments.numCharacters
)
)
/>
<
cfset
var
index
=
0
/>
<
cfloop
from
=
"1"
to
=
"#arguments.numCharacters#"
index
=
"index"
>
<
cfset
result.append
(chars.charAt
(random.nextInt
(chars.length
(
)
)
)
)
/>
</
cfloop
>
<
cfreturn
result.
toString
(
)
/>
</
cffunction
>
</
cfcomponent
>
To use this random key generator, you would do something like the following.
< cfset key = createObject ( "component", "RandomId" ).generate ( ) />
Happy coding!
+