Not yet rated
Tags:

Problem

You want to generate a random password for a user. For example they may have forgotten their current password and have requested a new one.

Solution

This is a simple example of some code that will generate a random password, 3 characters long from the letters A to Z.

Detailed explanation

The Chr() function in ColdFusion converts a number to the equivalent ASCII character. You can see a list of characters and the corresponding entity number on the w3schools website:  http://www.w3schools.com/tags/ref_ascii.asp

This example generates a password, which is 3 characters long using upper case letters. You can however use uppercase, lowercase and numbers if you wish.

The entity number for a capital "A" is 65, and the entity number for a capital "Z" is 90. We can use the RandRange function to pick a random number between 65 and 90, and then convert that to a letter.

<cfscript>
newpassword = Chr(RandRange(65,90)) & Chr(RandRange(65,90)) & Chr(RandRange(65,90));
</cfscript>

For longer passwords, you'd really want to use a loop instead of building the new password all in one line of code. 

If you want more sophisticated ways to generate passwords then I recommend that you look at two functions on cflib.org.

http://www.cflib.org/udf/MakePassword
http://www.cflib.org/udf/generatePassword

Further documentation for the Chr() and RandRange() functions is available on the Adobe site:

CHR()
RandRange()


+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes