Home >Backend Development >PHP Tutorial >How Can I Encrypt and Decrypt Strings in PHP Securely?
How do you Encrypt and Decrypt a PHP String?
Encrypting a PHP string involves converting the original string into an encrypted format using a key or salt. Decrypting the string requires the same key or salt to retrieve the original string.
Encryption Process
Decryption Process
Key Considerations
Example using Libsodium:
<?php use Sodium\Crypto; function encrypt(string $message, string $key): string { $nonce = random_bytes(Crypto::SECRETBOX_NONCEBYTES); $encrypted = Crypto::secretbox($message, $nonce, $key); return base64_encode($nonce . $encrypted); } function decrypt(string $encrypted, string $key): string { $decoded = base64_decode($encrypted); $nonce = substr($decoded, 0, Crypto::SECRETBOX_NONCEBYTES); $ciphertext = substr($decoded, Crypto::SECRETBOX_NONCEBYTES); $decrypted = Crypto::secretbox_open($ciphertext, $nonce, $key); return $decrypted; } $message = 'Hello, world!'; $key = random_bytes(Crypto::SECRETBOX_KEYBYTES); $encrypted = encrypt($message, $key); $decrypted = decrypt($encrypted, $key); var_dump($encrypted); var_dump($decrypted);
The above is the detailed content of How Can I Encrypt and Decrypt Strings in PHP Securely?. For more information, please follow other related articles on the PHP Chinese website!