Home >Backend Development >PHP Tutorial >How to Securely Encrypt and Decrypt Data Using PHP?
How to Securely Encrypt and Decrypt Passwords in PHP
Storing sensitive user information, such as foreign account credentials, requires special precautions to ensure data security. While encryption provides a layer of protection, it's crucial to employ robust methods that prevent unauthorized access to plaintext data.
Hashing vs. Encryption
Hashing is the preferred approach for password storage. Unlike encryption, hashing irreversibly transforms passwords into a unique and non-reversible format, making it virtually impossible to retrieve the original password. This ensures that even if attackers gain access to the hashed passwords, they cannot compromise the user accounts.
Encryption and Decryption Functions
For situations where encryption is necessary, PHP provides several functions to encrypt and decrypt text. One common method is the Rijndael cipher, also known as AES-128:
$key = 'password to (en/de)crypt'; $string = ' string to be encrypted '; // note the spaces
To Encrypt:
$iv = mcrypt_create_iv( mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_DEV_URANDOM ); $encrypted = base64_encode( $iv . mcrypt_encrypt( MCRYPT_RIJNDAEL_128, hash('sha256', $key, true), $string, MCRYPT_MODE_CBC, $iv ) );
To Decrypt:
$data = base64_decode($encrypted); $iv = substr($data, 0, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC)); $decrypted = rtrim( mcrypt_decrypt( MCRYPT_RIJNDAEL_128, hash('sha256', $key, true), substr($data, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC)), MCRYPT_MODE_CBC, $iv ), "" );
Warning
Encrypted data is vulnerable to padding oracle attacks if not authenticated. Authenticated encryption mechanisms should always be used in conjunction with encryption.
Best Practices
To ensure the highest level of security, follow these best practices:
The above is the detailed content of How to Securely Encrypt and Decrypt Data Using PHP?. For more information, please follow other related articles on the PHP Chinese website!