By Dexter Clark
Storing passwords correctly has always been important but is still something companies like Sony overlook. We know that we shouldn’t store passwords as plain text (hopefully) but is using something simple like md5 enough? The answer is NO if you really want a database full of secure passwords! Luckily Rails has a built-in method (in conjunction with a great gem: bcrypt) to create incredibly secure passwords.
The first thing we need to think about when creating secure passwords is encrypting them, altering the characters so that they can’t just be read. There are varying strengths of encryptions out there and the stronger the encryption, the harder it will be to decrypt for attackers. Bcrypt has incredibly strong encryption to it but just encrypting a password isn’t enough. An attacker could use the very same algorithm to create a table of passwords to check the password they took from you. So, we can create a salt (a random bit of data) that we can add to the users’ password so that the encryption will be different even when the passwords are the same, this makes it almost impossible for an attacker to have a database of possible passwords. Bcrypt automatically adds a salt for us, thus giving us especially secure passwords!
To use Bcrypt the first step is including it in our gem-file.
Then, we run bundle install and we should have Bcrypt installed. Next, we are going to need a model with a password but using this system we are going to need a field in our database called “password_digest”. password_digest will store our salted and encrypted passwords.
Now we need two things from the user, a password and a confirmation password. Just like we were required to have a password in the database to be called password_digest, it needs the passwords being passed to have specific names: password and password_confirmation (these should be the names in the form).
The last step for creation is having the method has_secure_password in your model. That’s it! This method will verify that password and password_confirmation are the same and use Bcrypt to salt and encrypt the password before storing it into the password_digest field. If you follow this, you will definitely be storing passwords in a secure way.