Encrypting Passwords
In this tutorial i will show you how you can easily encrypt and decrypt passwords using coldfusion
The first think we need to do is create in encryption password, this is what will be used to encrypt and unencrypt your password. If you loose this then you will not be able to unencrypt any of your encrypted data.
To create this key i will use an application variable so it can be called when needed
Ok, now i will show you how to encrypt your data, this is best done when saving the data to a database. I have a form to add new users so i post this form and just before we insert the data to the database we will encrypt the password with the encryption key
I have assumed that you all know how to make a basic form if you are at the level of encrypting passwords so i shall skip that part.
<cfquery datasource="encryption">
INSERT INTO users (username, password)
VALUES (<cfqueryparam value="#FORM.Nusername#" cfsqltype="cf_sql_clob" maxlength="255">, "#Encrypted#")
</cfquery>
<cflocation url="/Admin/users.cfm" addtoken="yes">
Ok so now we should have a database with a username and encrypted password, but for the users to be able to login we will need to decrypt this password.
This is basicly the same process as before, but we unencrypt the value and use the #Encrypted# variable insted of the #FORM.Password#
<cfquery name="Login" datasource="encryption">
SELECT *
FROM users
WHERE username = '#FORM.username#'
AND password = '#Encrypted#'
</cfquery>
Hope this code is of help to people


Of course if you are using MS SQL 2005 or 2008 Server you can use the Hash function for one way encryption and then there's no need to store the key in your code on the web server.
just means if anyone does manage to hack your database it makes it harder for them to get data.
It actually does matter whether you store a password encrypted vs hashed. For the primary reason that encryption IS reversible. A hash is not. All a hacker needs to get at every single password in your database is that one encryption key(of course after compromising the DB).
Even for login information, there is no reason to store the password encrypted, if you store it hashed, then when the user tries to log in again, you hash their input, and compare it to the hash in the database. If they match, then the entered the correct password. There is never a reason to decrypt the users password.
Also, you should be salting your users passwords before hashing to defeat weak password, brute force attacks and Birthday/Rainbow table attacks.
I recently had to recode an application that a junior developer had written because there were security holes everywhere of which he was unaware. He'd used 2 way encryption because he thought it would be useful to email a user their password if they forgot it. What he didn't consider was the insecure nature of email itself. IMHO it's far better to use hash encryption and send a user a temporary password if and when necessary.