Senior LevelPHP 8+
How do you implement authenticated public-key encryption in PHP 7.2+ using ext-sodium (libsodium)?
❓ Interview Prompt: Explain modern PHP cryptography with ext-sodium (libsodium), sodium_crypto_box, sealed boxes, and XSalsa20-Poly1305 authenticated encryption.
Legacy cryptographic functions ('mcrypt', manual AES-CBC without HMAC) suffer from padding oracle vulnerabilities and side-channel timing attacks. Since PHP 7.2, 'ext-sodium' (libsodium) is built into the PHP core as the standard cryptography library.
Key Capabilities:
•
Authenticated Encryption (AEAD): Uses XSalsa20-Poly1305 to guarantee both data confidentiality AND tamper-proof authenticity.
•
Sealed Boxes ('sodium_crypto_box_seal'): Encrypts messages using a recipient's public key without requiring the sender to have a private key.
Code Implementation Example
php
<?php
// Generate keypair
$keypair = sodium_crypto_box_keypair();
$publicKey = sodium_crypto_box_publickey($keypair);
$secretKey = sodium_crypto_box_secretkey($keypair);
// 1. Encrypt message using Sealed Box (Anonymous public key encryption)
$message = "Sensitive Credit Card Data";
$ciphertext = sodium_crypto_box_seal($message, $publicKey);
// 2. Decrypt message using Keypair
$decrypted = sodium_crypto_box_seal_open($ciphertext, $keypair);
echo $decrypted; // Outputs: Sensitive Credit Card Data💡Authenticated encryption and decryption using PHP ext-sodium sealed boxes.
🎯 Interview Key Takeaway
Use ext-sodium (libsodium) for modern authenticated encryption (sodium_crypto_box_seal) resistant to timing side-channel attacks.
#libsodium#ext-sodium#Cryptography#Security#Senior
Back to all PHP 8+ Questions→