http://www.perlmonks.org?node_id=961371


in reply to Password Encryption and Decryption

The thing about passwords is that you don't need to encrypt/decrypt them. Instead, all you need to do is store a cryptographic hash (also known as a "message digest") of the password. A hash cannot be 'decrypted' back to the original plain text but when you want to validate a login attempt, you just hash the supplied password and compare the result to the hash you have stored.

So for example if you want to accept the password "SmokeScreen" you might use the SHA1 hashing algorithm like this:

use Digest::SHA1 qw(sha1_hex); print sha1_hex("SmokeScreen"), "\n"; # Prints "95cb0bfd2977c761298d9624e4b4d4c72a39974a"

You could then store this 40 character string.

Later when someone attempts to log in they'll provide a plaintext password which you'll feed through the same sha1_hex function and if the result is the same 40 character string then they obviously supplied the right password.

A flaw with this plan is that if two people have the same password then they'll have the same 40 character hash (even on another server that uses the same hashing algorithm) - this could be useful information to an attacker.

A slightly more complex approach is to generate a few bytes of random "salt" when you initially hash the password. You'll add the salt bytes on the start of the plaintext before hashing and also on the start of the hash that you store. Then to validate a password you take the salt value from the stored hash and add it on the start of what the user provides. Because the salt bytes are random at the time the password is initially set, then two people with the same password will have different hash values.