17: Encrypt IP Addresses with Sodium
Overview
Section titled “Overview”Round-trip a documentation IP address through Sodium’s IP encryption functions. Select a mode based on which relationships the stored ciphertext needs to reveal.
Prerequisites
Section titled “Prerequisites”- PHP 8.6 CLI. Confirm the version with
php --version. - The
sodiumextension with IP encryption support. - Review the previous chapter if you’re following the series in order.
Allow about 10 minutes for the walkthrough and exercise.
What You’ll Build
Section titled “What You’ll Build”A runnable sodium-ipcrypt.php example.
Step 1: Run the example (~5 min)
Section titled “Step 1: Run the example (~5 min)”Run the following from the root of the Code with PHP repository.
php code/php-8-6/17-sodium-ipcrypt/sodium-ipcrypt.php<?php
declare(strict_types=1);
$ip = '192.0.2.15';
$key = sodium_crypto_ipcrypt_keygen();echo 'Deterministic: ', sodium_crypto_ipcrypt_decrypt(sodium_crypto_ipcrypt_encrypt($ip, $key), $key), PHP_EOL;
$ndKey = sodium_crypto_ipcrypt_nd_keygen();echo 'ND: ', sodium_crypto_ipcrypt_nd_decrypt(sodium_crypto_ipcrypt_nd_encrypt($ip, $ndKey), $ndKey), PHP_EOL;
$ndxKey = sodium_crypto_ipcrypt_ndx_keygen();echo 'NDX: ', sodium_crypto_ipcrypt_ndx_decrypt(sodium_crypto_ipcrypt_ndx_encrypt($ip, $ndxKey), $ndxKey), PHP_EOL;
$prefixKey = sodium_crypto_ipcrypt_pfx_keygen();echo 'PFX: ', sodium_crypto_ipcrypt_pfx_decrypt(sodium_crypto_ipcrypt_pfx_encrypt($ip, $prefixKey), $prefixKey), PHP_EOL;
echo 'Binary round trip: ', sodium_bin2ip(sodium_ip2bin($ip)), PHP_EOL;Expected Result
Section titled “Expected Result”Deterministic: 192.0.2.15ND: 192.0.2.15NDX: 192.0.2.15PFX: 192.0.2.15Binary round trip: 192.0.2.15Why It Works
Section titled “Why It Works”The default mode preserves the address format and repeats the same output for the same address and key. The randomized ND and NDX modes use a fresh tweak and produce longer ciphertexts. The PFX mode preserves shared prefixes, which can support subnet analysis and also reveals subnet relationships.
Exercise
Section titled “Exercise”Replace the IPv4 input with 2001:db8::5 and confirm all modes still round-trip. Compare sodium_ip2bin() output lengths for the IPv4 and IPv6 examples.
Wrap-up
Section titled “Wrap-up”Continue with Extend Hash Output with SHAKE and TurboSHAKE.