Home >Backend Development >PHP Tutorial >How Can PHP Securely Encrypt and Decrypt Data, and How Does it Handle Password Hashing?
Encryption and Decryption in PHP
Encrypting Sensitive Data
PHP offers various encryption algorithms and methods to protect sensitive data stored in databases. You can encrypt specific fields, such as Fname, Lname, and Email, using symmetric ciphers like AES-256-CBC. Additionally, you need to generate an initialization vector (IV) for each encryption operation and store it for decryption.
Decryption Process
To decrypt the encrypted data, follow a similar process. You'll need the same encryption key and IV used during encryption. Decryption yields the original plaintext values.
One-Way Hashing with SHA256 and Salt
For password security, you can hash passwords using SHA256 in conjunction with a strong salt. Implement a function that generates a random salt and combines it with the password before hashing. This adds an extra layer of protection against brute-force attacks.
Example:
function generatePasswordHash($password) { $salt = bin2hex(openssl_random_pseudo_bytes(16)); return hash('sha256', $salt . $password) . $salt; }
Verifying Passwords
When verifying passwords, use a constant-time comparison function to avoid timing attacks. For each login attempt, re-hash the provided password using the same salt as the original hash and compare the results.
Example:
function verifyPassword($suppliedPassword, $storedHash) { $saltedPassword = substr($storedHash, 64); return hash('sha256', $saltedPassword . $suppliedPassword) == $storedHash; }
The above is the detailed content of How Can PHP Securely Encrypt and Decrypt Data, and How Does it Handle Password Hashing?. For more information, please follow other related articles on the PHP Chinese website!