Home >Backend Development >PHP Tutorial >How Can I Implement Simple Two-Way Encryption and Authentication in PHP?
Caution: Avoid encrypting passwords using these methods; instead, employ password hashing algorithms for safe password storage.
When using PHP 5.4 or later and desiring code portability, utilize an existing library providing authenticated encryption. Openssl methods, such as openssl_encrypt() and openssl_decrypt(), can be employed once you've selected an encryption method.
Consider using the Advanced Encryption Standard (AES) in CTR mode for encryption. This method offers the best balance between security and performance. Consult openssl_get_cipher_methods() for a list of supported methods.
The following PHP class provides a simple encryption/decryption wrapper using OpenSSL:
class UnsafeCrypto { const METHOD = 'aes-256-ctr'; public static function encrypt($message, $key, $encode = false) { // ... if ($encode) { return base64_encode($nonce.$ciphertext); } return $nonce.$ciphertext; } public static function decrypt($message, $key, $encoded = false) { // ... $plaintext = openssl_decrypt( $ciphertext, self::METHOD, $key, OPENSSL_RAW_DATA, $nonce ); return $plaintext; } }
For enhanced security, implement authentication to verify encrypted data's integrity:
class SaferCrypto extends UnsafeCrypto { const HASH_ALGO = 'sha256'; public static function encrypt($message, $key, $encode = false) { // ... if ($encode) { return base64_encode($mac.$ciphertext); } // Prepend MAC to the ciphertext and return to caller return $mac.$ciphertext; } public static function decrypt($message, $key, $encoded = false) { // ... $calculated = hash_hmac( self::HASH_ALGO, $ciphertext, $authKey, true ); if (!self::hashEquals($mac, $calculated)) { throw new Exception('Encryption failure'); } // Pass to UnsafeCrypto::decrypt $plaintext = parent::decrypt($ciphertext, $encKey); return $plaintext; } }
The above is the detailed content of How Can I Implement Simple Two-Way Encryption and Authentication in PHP?. For more information, please follow other related articles on the PHP Chinese website!