Encrypting and Decrypting PHP Strings
Question:
How can we encrypt and decrypt a PHP string, requiring both an original string and a salt or key for both processes?
Answer:
It's crucial to understand the difference between encryption and authentication before proceeding. For robust security, we recommend encrypted authentication, which entails encrypting and then authenticating.
Avoid creating your own cryptography; instead, utilize a dependable library developed by cryptography specialists. We strongly advise using libsodium or defuse/php-encryption due to their ease of use and built-in authenticated encryption.
Encryption Steps:
Decryption Steps:
Design Considerations:
When Not to Use Encryption:
Libsodium PHP Example:
function safeEncrypt(string $message, string $key): string { if (mb_strlen($key, '8bit') !== SODIUM_CRYPTO_SECRETBOX_KEYBYTES) { throw new RangeException('Key is not the correct size (must be 32 bytes).'); } $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); $cipher = base64_encode( $nonce. sodium_crypto_secretbox( $message, $nonce, $key ) ); return $cipher; }
Libsodium Decryption:
function safeDecrypt(string $encrypted, string $key): string { $decoded = base64_decode($encrypted); $nonce = mb_substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit'); $ciphertext = mb_substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit'); $plain = sodium_crypto_secretbox_open( $ciphertext, $nonce, $key ); return $plain; }
defuse/php-encryption Example:
use Defuse\Crypto\Crypto; use Defuse\Crypto\Key; $message = 'We are all living in a yellow submarine'; $key = Key::createNewRandomKey(); $ciphertext = Crypto::encrypt($message, $key); $plaintext = Crypto::decrypt($ciphertext, $key);
The above is the detailed content of How to Securely Encrypt and Decrypt PHP Strings Using Libsodium or defuse/php-encryption?. For more information, please follow other related articles on the PHP Chinese website!