PHP - Encryption and decryption function

Data encryption doesn’t make your software secure or your user’s confidential information safe from hacker, as the data encryption is designed to be reversible (ability to decrypt) in order to get back the original data when a correct decryption key (password) is provided. But what the data encryption can do for you is to harden the process, increase the security level, hide the sensitive content or confidential information in unreadable text from the normal eyes.

Data encryption function

This function is to encrypt any data string. You need to provide a password because you gonna need it when you want to decrypt back the encrypted string.

Please note that, every time the function Encrypt() is executed, with the same password and same data string, the encrypted string (output) is always get changed as the mt_rand() function is used for generating the salt.

Here are the example outputs of the encrypted string (same data) after I executed it for 3 times:-

<?phpechoDecrypt('myPass123','U2FsdGVkX19LYv5Y5EDmFbjH8bGMDFwlid30h2x1ybibT1Dwp0vekJ0OT4tb7/j6');echoDecrypt('myPass123','U2FsdGVkX1/3zxJCcE8p89t67nJNp8blNkezNxTVn4IDFQLM755K2+OSfFHewDLI');echoDecrypt('myPass123','U2FsdGVkX18OQ8puUN8BBi+d6vAjEzDTZqM2WaKQD1atOykkYl9MY7NQM1DqI4Kw');// All of three above will output the same decrypted data: Welcome to Flippancy 25?>

Please note that, for each encryption and decryption, they requires the same password to work in the expected result.

Data encryption is NOT for password!

Data encryption would be useful for something like social security number, phone number, bank account number, credit card information, and so on. But it’s practically insecure for a USER PASSWORD!

Hashing algorithm for securing user password

To secure the user password, the best practice is to implement a one-way hashing algorithm technique, which means it cannot be decrypted (irreversible). Unlike the encryptions, they are formulated to be able to be decrypted. In PHP, it’s recommended to use the built-in functions to securely hash the user password such as password_hash or crypt.

But you want to implement a custom function, you can use this snippet:

Another thing you can do to add extra layer of security is to enforce the strong password for the user or you can provide two-factor authentication service. If you are keen to learn more about password hashing, I recommend you to read this article. It is a very good article talking about salted password hashing.