For most of us, web developers, the encryption and decryption of strings in the www is a known mandatory fact. But we all straggling to find the best way to approach the situation.
There are many ways to encrypt strings (and when i say “strings” i mean “Passwords” mostly), and they all can achieve the same goal, but each solution comes with the same problems :
- Lack of documentation.
- No way to make the same call from different scripts with the same encryption.
- Hard maintenance and spaghetti code.
This is why i am giving you a suitable solution. To be honest, the attached class and documentation are a Puzzle from several scripts and tutorials a read and learned in order to give you the best solution I can think of.
We all agree that
mcrypt_* functions are the best way to create an encrypted strings, and we can wrap the
mcrypt_decrypt with md5 or base64 extra encryption, but this is a “Later on” subject we will discuss in a later article.
You can find a great explanation for mcrypt in here.
So, not lets start talking about the solution i give here.
This is a simple class with simple logic, because i don’t think this should be heavy on logic, for performance reasons.
The class attached is a small class with 3 methods :
- encrypt – The encryption function, returns the encrypted String.
- decrypt – The decryption function, returns the original String.
- generateKey – Generates a cipher key to give the encryption and decryption functions.
The zipped file attached includes a complete example page to make you familiar with the logic of this class.
There are 2 ways to work with it :
Encrypt and decrypt on the same script – This will not need you to give the class a key to remember, because the script will encrypt and decrypt with the same instance of the class. I don’t see a use for this, but who am i to prevent it from you?
Encrypt once and decrypt later – This is the main use of the class. When you create an encrypted password you will get the encryption key for later use. You can instantiate a new class and retrieve the original string by giving the constructor of the new instance the key you received when created the encrypted string.
Great news ya all (12/03/2014)
This script downloaded tonight for the 1000th time. I got several emails asking for more “muscles” to the original script, and i will work on it soon. Meanwhile, take a look at my latest post about PHP 5.6 migration, and start upgrading.. There is only forward in our field of expertise 🙂