Lab 08: Security — libsodium

Time: 60 minutes | Level: Architect | Docker: docker run -it --rm php:8.3-cli bash

Overview

PHP 7.2+ ships with the libsodium extension built-in. Sodium provides modern, audited cryptographic primitives: authenticated encryption, digital signatures, key exchange, and password hashing. This lab covers all major Sodium functions with real verification.


Step 1: Sodium Overview

<?php
// libsodium is always available in PHP 7.2+
echo "Sodium version: " . SODIUM_LIBRARY_VERSION . "\n";
echo "Major:          " . SODIUM_LIBRARY_MAJOR_VERSION . "\n";

// Key sizes
echo "\n=== Key Sizes ===\n";
echo "secretbox key:    " . SODIUM_CRYPTO_SECRETBOX_KEYBYTES . " bytes\n";
echo "secretbox nonce:  " . SODIUM_CRYPTO_SECRETBOX_NONCEBYTES . " bytes\n";
echo "sign public key:  " . SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES . " bytes\n";
echo "sign secret key:  " . SODIUM_CRYPTO_SIGN_SECRETKEYBYTES . " bytes\n";
echo "box public key:   " . SODIUM_CRYPTO_BOX_PUBLICKEYBYTES . " bytes\n";
echo "pwhash salt:      " . SODIUM_CRYPTO_PWHASH_SALTBYTES . " bytes\n";
echo "generichash key:  " . SODIUM_CRYPTO_GENERICHASH_KEYBYTES . " bytes\n";

📸 Verified Output:


Step 2: Authenticated Symmetric Encryption — XSalsa20-Poly1305

📸 Verified Output:


Step 3: Ed25519 Digital Signatures

📸 Verified Output:


Step 4: Asymmetric Encryption — X25519 + XSalsa20-Poly1305


Step 5: Argon2id Password Hashing

📸 Verified Output:

💡 Use SENSITIVE ops/mem for highly sensitive data (private keys, HSM-grade). Use INTERACTIVE for login flows where UX matters. Never use less than INTERACTIVE.


Step 6: BLAKE2b Hashing & MACs


Step 7: Secure Random & Memory Safety


Step 8: Capstone — Encrypted JWT-Style Token System

📸 Verified Output:


Summary

Operation
Function
Algorithm

Symmetric encrypt

sodium_crypto_secretbox()

XSalsa20-Poly1305

Symmetric decrypt

sodium_crypto_secretbox_open()

XSalsa20-Poly1305

Sign message

sodium_crypto_sign()

Ed25519

Verify+extract

sodium_crypto_sign_open()

Ed25519

Detached sign

sodium_crypto_sign_detached()

Ed25519

Verify detached

sodium_crypto_sign_verify_detached()

Ed25519

Asymmetric encrypt

sodium_crypto_box()

X25519+XSalsa20-Poly1305

Sealed box

sodium_crypto_box_seal()

Anonymous sender

Password hash

password_hash(PASSWORD_ARGON2ID)

Argon2id

Key derivation

sodium_crypto_pwhash()

Argon2id

Generic hash

sodium_crypto_generichash()

BLAKE2b

Zero memory

sodium_memzero()

Secure wipe

Secure random

random_bytes()

OS CSPRNG

Last updated