We will see how to encrypt information in PHP in order to store and exchange it safely. But first, we’ll do a little reminder on symmetric cryptography.
Encryption is an operation which is to alter the information to make it unreadable, but reversibly only to a specific person, who is able to decrypt that information by restoring its original form.
How did you decrypt and therefore access this information?
The answer is simple: when encrypts the information, we will use an encryption key. And this encryption key also allows you to do the opposite: to do decrypt the information.
AES encryption with PHP
After this little essential reminder on cryptography, we will be able to attack the practice.
We’ll see how encrypt and decrypt with the algorithm Rijndael , which is used for standard AES, thanks to the bookstore libmcrypt .
To do this properly, we will put everything in a class that will serve as a “Namespace” (although it is not object oriented programming because all the members are static)
<?php class Chiffrement { private static $cipher = MCRYPT_RIJNDAEL_128; // Algorithm used for the encryption blocks private static $key = 'use a encryption key you like'; // Encryption Key private static $mode = 'cbc'; // Procedure (processing blocks) public static function crypt($data){ $keyHash = md5(self::$key); $key = substr($keyHash, 0, mcrypt_get_key_size(self::$cipher, self::$mode) ); $iv = substr($keyHash, 0, mcrypt_get_block_size(self::$cipher, self::$mode) ); $data = mcrypt_encrypt(self::$cipher, $key, $data, self::$mode, $iv); return base64_encode($data); } public static function decrypt($data){ $keyHash = md5(self::$key); $key = substr($keyHash, 0, mcrypt_get_key_size(self::$cipher, self::$mode) ); $iv = substr($keyHash, 0, mcrypt_get_block_size(self::$cipher, self::$mode) ); $data = base64_decode($data); $data = mcrypt_decrypt(self::$cipher, $key, $data, self::$mode, $iv); return rtrim($data); } } ?>
And this is how it is used:
<?php $clair = "Salut !"; $crypt = Chiffrement::crypt($clair); $decrypt = Chiffrement::decrypt($crypt); ?> <pre> clair : <?php echo $clair; ?> crypt : <?php echo $crypt; ?> raw crypt : <?php echo base64_decode($crypt); ?> decrypt : <?php echo $decrypt; ?> </pre>
The operation is very simple: to encrypt and decrypt with mcrypt, just use the functions mcrypt_encrypt
and mcrypt_decrypt
.
My these functions take a lot of parameters, which are most always the same for encryption and decryption, except $data
of course (which contains the variable to encrypt).
So far pooling all in static variables within a class:
- cipher
This setting tells how mcrypt encryption algorithm used. Indeed, libmcrypt offers many encryption algorithms (just over 40), you will find the list here: mcrypt.ciphers.php - Key
This parameter is simply the encryption key which I mentioned above, which is used to encrypt and decrypt the message.
And that’s not entirely true, you can not use any any string in key size is fixed and depends on the algorithm used.
Rather than directly using a key, which look like this:a7af2934b9c8ca2e346314bea5cf3a8f
a string is used much easier to remember, making office word password .
Then a valid key you will generate from this password with a simple hash function,md5
in this case. You have to choose your password features, and it must remain secret - Mode
The procedure, another key concept (dare I say) cryptography.
We will see below what it is.
Also, I used functions base64_encode
and base64_decode
to “encapsulate” the encrypted data (and same for decrypt, inevitably, since it is the reciprocal). It is not mandatory, and it is by no means an additional security measure. This is just to avoid encoding problems (character) because special characters. Base64 produces character strings that only use 64 ASCII characters that are compatible with all charset (latin1, utf8 …).
It avoids trashing the encrypted data by storing it in a mysql database or a mismatched file.
UNANSWERED QUESTIONS
Question 1.
What does the password_verify() function do?
The password_verify() function is designed to compare and verify if a password matches a previously generated hash. By utilizing this function, you can determine whether a provided password is correct or not. The function returns a boolean value of true if the password and hash match, indicating that the provided password is valid. Conversely, if the password and hash do not match, the function returns false, indicating that the provided password is incorrect. This provides a secure and reliable method for password authentication and verification.
Question 2.
What is the syntax of the password_verify() function?
The syntax of the password_verify() function is as follows:
bool password_verify(string $password, string $hash)
The password_verify() function takes in two parameters: $password
and $hash
. The $password
parameter represents the password that needs to be verified, while the $hash
parameter represents the hashed version of the password.
This function is used to verify whether the given hash matches the given password. It is typically used to compare a user-entered password with its corresponding hashed version stored in a database, for authentication purposes.
If the password and the hash match, the function will return true. On the other hand, if they do not match, the function will return false.
To use this function, simply pass the password and the corresponding hash to it, and then evaluate the return value to determine whether the password is valid or not.
Question 3.
How can we decrypt a password hash in PHP?
To decrypt a password hash in PHP, you can use the password_verify() function. This function takes two arguments: the password in plaintext form and the hashed password you want to compare it with. Here are the steps to decrypt a password hash:
- Start by obtaining the plaintext password entered by the user. For example:
$unencrypted_password = "Cloudways@123";
- Fetch the hashed password from your database or any other storage where it is stored. For example:
$hash = "2y10D6pwJsA5KKdUs7tlrIC3z.we7QZR58wx9gEiuLlQ/dr7E/Rtnj9Ce";
- Use the password_verify() function, passing the plaintext password and hashed password as arguments. This function will compare the two values and return true if they match, or false otherwise. For example:
$verify = password_verify($unencrypted_password, $hash);
- Finally, you can check the result of the verification and act accordingly. If the password and hash match, you can consider the password as decrypted. For example:
if ($verify) {echo 'Correct Password!';} else {echo 'Password is Incorrect';}
By following these steps, you can successfully decrypt a password hash in PHP using the password_verify() function.
Question 4.
What is the generated hash code?
The generated hash code is a secure alphanumeric string that consists of both upper and lower-case letters, numbers, and possibly special characters. In this particular case, the generated hash code is “2y10D6pwJsA5KKdUs7tlrIC3z.we7QZR58wx9gEiuLlQ/dr7E/Rtnj9Ce”.
Question 5.
How can passwords be encrypted and decrypted using PHP?
To encrypt and decrypt passwords using PHP, one effective approach is to utilize the password_hash and password_verify functions. These functions provide a convenient and secure way to safeguard passwords. Here is an explanation of how to implement this:
- Generate a Hashed Password:
- Begin by defining the password to be encrypted, for example: $unencrypted_password = “Cloudways@123″;
- Use the password_hash function, which automatically generates a hash of the password.Example: $hash = password_hash($unencrypted_password, PASSWORD_DEFAULT);
- The PASSWORD_DEFAULT algorithm is recommended, as it ensures compatibility with future PHP versions.
- Store the Hashed Password:
- Save the generated hash code, $hash, in your database for future reference.
- This ensures that the original password is not stored directly and provides an added layer of security.
- Verify the Password:
- When a user attempts to log in and enters their password, retrieve the corresponding hash from the database.
- Use the password_verify function to compare the entered password with the stored hash.Example: $is_match = password_verify($entered_password, $stored_hash);
- The $is_match variable will be true if the entered password matches the stored hash, and false otherwise.
By following this approach, passwords are securely encrypted and can be easily verified during the login process. It is important to note that the password_hash function automatically includes a random salt, which enhances security by making each hash unique. Additionally, this process eliminates the need for a separate decryption step, as passwords are stored in a one-way hash format that cannot be reversed.
Question 6.
How does MySQL encrypt PHP passwords?
MySQL encrypts PHP passwords by using a hashing function called Password(). When creating a new user account with the CREATE USER command, MySQL takes the provided password (IDENTIFIED BY) and internally applies the Password() function to generate a hashed value. This hashed value is stored in the MySQL database, rather than the actual plaintext password.
However, it is worth noting that the Password() function in MySQL is considered to be relatively weaker in terms of encryption. The MySQL documentation itself recommends using alternative encryption methods, such as SHA1 or Hash(), as they provide stronger encryption. Additionally, a random salt per password is suggested to further enhance security and prevent the creation of precomputed rainbow tables based on common salts.
In summary, while MySQL does provide password encryption through the Password() function, using stronger methods like SHA1 or Hash(), along with random salts, is recommended for greater security when encrypting PHP passwords in MySQL.
Question 7.
Why is PHP encryption important for data protection?
PHP encryption is of utmost importance for data protection due to the significant role it plays in safeguarding sensitive information. In today’s digital age, where personal and business data is commonly stored on cloud servers, the need for robust encryption has become paramount.
One primary reason for prioritizing PHP encryption is the ability to securely protect data that should remain inaccessible to unauthorized individuals. By utilizing encryption techniques, sensitive information can be encoded and transformed into an unreadable format, ensuring that even if it falls into the wrong hands, it remains useless and indecipherable.
For businesses, the repercussions of inadequate encryption can be quite severe. A breach in the security of classified business data can inflict substantial damage, providing competitors with an unfair advantage. Additionally, the leakage of customers’ information extends beyond a mere public relations nightmare. It can result in legal actions and even the dissolution of a company. Consequently, a PHP application that lacks proper encryption measures puts both the organization and its stakeholders at risk.
Effective PHP encryption involves implementing tough-to-crack password encryption. This additional layer of protection ensures that even if an unauthorized individual gains access to encrypted data, they would still require the correct password or key to decrypt it. Consequently, this serves as a vital security feature that customers expect from any PHP application.
In conclusion, the significance of PHP encryption for data protection cannot be overstated. It allows businesses and individuals to secure their sensitive information, especially in the era where cloud storage has become prevalent. Failure to implement proper encryption measures can result in severe consequences such as financial losses, lawsuits, and reputational damage. Thus, prioritizing PHP encryption is essential in safeguarding data and maintaining the trust of customers and stakeholders.