Encrypting and Decrypting Strings in PHP
Avoiding Common Pitfalls
Before delving into the implementation of encryption and decryption, it's crucial to understand the difference between encryption and authentication. For secure data protection, authenticated encryption is recommended over simple encryption. Additionally, it's advisable to avoid creating custom cryptography implementations and instead rely on secure and well-established libraries like libsodium or defuse/php-encryption.
Encryption and Decryption
Encryption:
Decryption:
Implementation with Libsodium
use Sodium\Crypto\SecretBox; $key = random_bytes(SecretBox::KEYBYTES); $nonce = random_bytes(SecretBox::NONCEBYTES); $ciphertext = SecretBox::encrypt($message, $nonce, $key); $plaintext = SecretBox::decrypt($ciphertext, $nonce, $key);
Implementation with defuse/php-encryption
use Defuse\Crypto\Crypto; use Defuse\Crypto\Key; $key = Key::createNewRandomKey(); $ciphertext = Crypto::encrypt($message, $key); $plaintext = Crypto::decrypt($ciphertext, $key);
Additional Considerations
Cautions
Example with Libsodium
use Sodium\Crypto\SecretBox; $key = random_bytes(SecretBox::KEYBYTES); $nonce = random_bytes(SecretBox::NONCEBYTES); $ciphertext = SecretBox::encrypt($message, $nonce, $key); $plaintext = SecretBox::decrypt($ciphertext, $nonce, $key); echo "Ciphertext: " . $ciphertext . PHP_EOL; echo "Plaintext: " . $plaintext . PHP_EOL;
The above is the detailed content of How Can I Securely Encrypt and Decrypt Strings in PHP Using Established Libraries?. For more information, please follow other related articles on the PHP Chinese website!