Logging IP Addresses Without Storing Them: PHP 8.6's ipcrypt in Laravel

PHP 8.6 ships ipcrypt in ext-sodium. Use php ipcrypt in Laravel for a format-preserving IP column, a custom cast, rate limiting and a key rotation command.

Steven Richardson
Steven Richardson
· 11 min read

Every Laravel app I have inherited logs IP addresses somewhere: an audit table, a login history, a visits row, a Sentry context. The column is varchar(45), it is indexed, and it is plaintext forever. Hashing breaks the queries, and Laravel's encrypted cast turns it into a base64 blob that no longer fits an inet column and makes "every request from this address" a full table scan.

PHP 8.6, due on 19 November 2026, adds a third option to ext-sodium: a cipher whose input and output are both IP addresses.

Check that your build actually has ipcrypt#

The ipcrypt functions are compiled into ext-sodium only when PHP is built against libsodium 1.0.21 or newer, which is where the crypto_ipcrypt_* primitives first appeared. A PHP 8.6 build on an older distro libsodium will have none of them, and the failure mode is a plain "undefined function" at runtime. Check for the constant rather than the function, because the whole block sits behind one #ifdef:

if (! defined('SODIUM_CRYPTO_IPCRYPT_KEYBYTES')) {
    throw new RuntimeException(
        'ext-sodium was built without ipcrypt support (needs libsodium >= 1.0.21).'
    );
}

Put that in an environment check command or a php artisan about entry. If you are planning the wider move, this slots into the same pass as the rest of the PHP 8.6 upgrade checklist for a Laravel app — it is a build flag question, not a code question, and the production image is the wrong place to discover it.

The twelve functions and their constants are listed in the PHP 8.6 UPGRADING notes under New Functions.

Generate a dedicated ipcrypt key#

Each variant has its own keygen and its own key length, and they are not interchangeable: deterministic and _nd_ take 16 bytes, _ndx_ and _pfx_ take 32. Passing the wrong length throws a SodiumException rather than silently truncating, which is the behaviour you want. Generate the key once, base64 it, and store it in its own environment variable:

php -r 'echo base64_encode(sodium_crypto_ipcrypt_keygen()), PHP_EOL;'
// config/ipcrypt.php
return [
    // Base64 of the raw 16-byte key. NOT derived from APP_KEY.
    'key' => env('IPCRYPT_KEY'),

    // Set during a rotation window; null the rest of the time.
    'previous_key' => env('IPCRYPT_PREVIOUS_KEY'),
];

Do not reuse APP_KEY. It rotates on a different schedule, it is readable by every package in the container, and — critically — rotating APP_KEY only invalidates sessions and cookies, whereas rotating the ipcrypt key invalidates every row in your audit table. Two keys, two lifecycles, two blast radii, which is the same argument as the rest of managing secrets in a Laravel production environment.

Choose the ipcrypt variant that matches your query patterns#

There are four modes, defined in the ipcrypt Internet-Draft, and the choice is driven entirely by what you need to do with the column afterwards. Run the same address through each and the difference is obvious:

$detKey = sodium_crypto_ipcrypt_keygen();      // 16 bytes
$ndKey  = sodium_crypto_ipcrypt_nd_keygen();   // 16 bytes
$pfxKey = sodium_crypto_ipcrypt_pfx_keygen();  // 32 bytes

// Deterministic: same input, same output. Output is a valid address,
// but an IPv4 input comes back in IPv6 form.
sodium_crypto_ipcrypt_encrypt('192.168.1.1', $detKey);
// e.g. "8e9f:1b3c:...:4a21" — stable across calls

// Non-deterministic: random 8-byte tweak per call, returned as 48 hex
// characters. Two calls on the same address never match.
sodium_crypto_ipcrypt_nd_encrypt('192.168.1.1', $ndKey);
// 48-char hex, different every time

// Prefix-preserving: keeps the address family and the subnet structure.
sodium_crypto_ipcrypt_pfx_encrypt('10.0.0.1', $pfxKey);   // valid IPv4
sodium_crypto_ipcrypt_pfx_encrypt('10.0.0.2', $pfxKey);   // shares its /24

Deterministic is the one you want for an audit table: equality still works, so where('ip', $needle) and group by ip behave exactly as before. _nd_ and _ndx_ give you unlinkable ciphertexts — nothing correlates two visits from the same address — but they return hex strings of 48 and 64 characters respectively, not addresses, and you cannot group on them at all. _pfx_ is the analytics choice: 10.0.0.1 and 10.0.0.2 encrypt to two addresses that still share a prefix, so /24-level aggregation survives.

That prefix preservation is a deliberate leak. If subnet structure is the thing you are trying to hide, _pfx_ is the wrong mode.

Store the pseudonymous address with a custom Eloquent cast#

The cast is where this stops being a crypto exercise and starts being a Laravel feature. get() decrypts so application code reads $log->ip as the real address; set() encrypts so nothing else in the stack ever sees a raw value heading for the database. The shape is identical to the built-in encrypted cast, except the stored value is still an IP address:

<?php

declare(strict_types=1);

namespace App\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;
use RuntimeException;

/**
 * @implements CastsAttributes<string|null, string|null>
 */
final class PseudonymousIp implements CastsAttributes
{
    public function get(Model $model, string $key, mixed $value, array $attributes): ?string
    {
        return $value === null
            ? null
            : sodium_crypto_ipcrypt_decrypt($value, self::key());
    }

    public function set(Model $model, string $key, mixed $value, array $attributes): ?string
    {
        return $value === null
            ? null
            : sodium_crypto_ipcrypt_encrypt($value, self::key());
    }

    private static function key(): string
    {
        // Strict mode: a mangled env var should fail loudly, not decode to junk.
        $key = base64_decode((string) config('ipcrypt.key'), true);

        if ($key === false || strlen($key) !== SODIUM_CRYPTO_IPCRYPT_KEYBYTES) {
            throw new RuntimeException('IPCRYPT_KEY is missing or not a 16-byte key.');
        }

        return $key;
    }
}

Wire it up on the model and leave the migration alone apart from the width:

// Migration — 45 characters, because an encrypted IPv4 comes back as IPv6 text.
$table->string('ip', 45)->index();

// app/Models/AuditLog.php
protected function casts(): array
{
    return ['ip' => PseudonymousIp::class];
}

On PostgreSQL, inet also works and is the better column type — it accepts both families, so the IPv4-in, IPv6-out behaviour is a non-issue there.

Pseudonymise the address in middleware before anything logs it#

The cast protects the database. It does nothing for the half-dozen other places an address leaks: the Monolog line, the Sentry request context, the Nightwatch payload. Set the pseudonymous value once per request and have the rest of the stack read that instead:

<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Context;
use Symfony\Component\HttpFoundation\Response;

final class AddPseudonymousIpToContext
{
    public function handle(Request $request, Closure $next): Response
    {
        $ip = $request->ip();

        if ($ip !== null) {
            $pseudonym = sodium_crypto_ipcrypt_encrypt($ip, self::key());

            // Available to logs, exception reports and any job dispatched downstream.
            Context::add('client_ip', $pseudonym);
            $request->attributes->set('pseudonymous_ip', $pseudonym);
        }

        return $next($request);
    }
}

Register it after TrustProxies in bootstrap/app.php. Order matters: behind a load balancer, $request->ip() returns the proxy address until TrustProxies has run, and pseudonymising your own ingress IP is a quiet way to end up with a column containing one distinct value. Because this uses Context, the value follows a dispatched job into the queue worker too — the same mechanism as request-scoped logging that survives into jobs.

Pair it with #[\SensitiveParameter] on any helper that handles the raw address, so a stack trace never prints what the database no longer holds. That attribute is worth applying broadly, as in redacting secrets from PHP stack traces.

Rate limit on the deterministic ciphertext#

Deterministic output is stable, which means it works as a rate limiter key without changing how limits behave. Same client, same ciphertext, same bucket — and the limiter state in Redis now holds a pseudonym rather than a real address:

// bootstrap/app.php or a service provider
RateLimiter::for('api', function (Request $request) {
    $key = $request->user()?->id
        ?? $request->attributes->get('pseudonymous_ip')
        ?? $request->ip();

    return Limit::perMinute(60)->by((string) $key);
});

Two caveats. Rate limiting by IP is already a blunt instrument behind CGNAT, and pseudonymising it does not make it sharper — the trade-offs in rate limiting Laravel API routes apply unchanged. And abuse blocklists that have to interoperate with something outside PHP — an nginx deny rule, a WAF, a fail2ban jail, the kind of setup in blocking malicious 404 scanners at the nginx layer — cannot read your ciphertext. Keep those keyed on real addresses in a short-lived store, and keep the long-lived audit table pseudonymous.

Prove the raw address never lands with a Pest test#

Two assertions matter: the round trip returns the original address, and the stored value is not the original address. The second is the one that catches a future developer quietly removing the cast:

<?php

use App\Models\AuditLog;
use Illuminate\Support\Facades\DB;

it('round-trips the address through the cast', function () {
    $log = AuditLog::create(['ip' => '203.0.113.42']);

    expect($log->fresh()->ip)->toBe('203.0.113.42');
});

it('never writes the raw address to the column', function () {
    AuditLog::create(['ip' => '203.0.113.42']);

    $stored = DB::table('audit_logs')->value('ip');

    expect($stored)
        ->not->toBe('203.0.113.42')
        ->and(filter_var($stored, FILTER_VALIDATE_IP))->not->toBeFalse();
});

it('groups identical addresses together', function () {
    AuditLog::create(['ip' => '203.0.113.42']);
    AuditLog::create(['ip' => '203.0.113.42']);

    expect(AuditLog::where('ip', '203.0.113.42')->count())->toBe(2);
});

That last test only passes with a deterministic variant, which makes it a useful guard: swap the cast to _nd_ by mistake and the suite tells you immediately.

Plan the key rotation before you need it#

Rotating the ipcrypt key rewrites every stored value, which is a very different operation from rotating APP_KEY. Write the command now, while the table is small enough that running it is cheap. Decrypt with the old key, re-encrypt with the new, and chunk by primary key so a long run does not hold one transaction open:

public function handle(): int
{
    $old = base64_decode((string) config('ipcrypt.previous_key'), true);
    $new = base64_decode((string) config('ipcrypt.key'), true);

    AuditLog::query()
        ->whereNotNull('ip')
        ->chunkById(1000, function ($logs) use ($old, $new): void {
            foreach ($logs as $log) {
                // Read the raw column: the cast would decrypt with the NEW key.
                $raw = $log->getRawOriginal('ip');

                $log->forceFill([
                    'ip' => sodium_crypto_ipcrypt_encrypt(
                        sodium_crypto_ipcrypt_decrypt($raw, $old),
                        $new,
                    ),
                ])->saveQuietly();
            }
        });

    return self::SUCCESS;
}

getRawOriginal() is the important line — going through the cast would decrypt with the new key and produce garbage that still looks like a valid address, so nothing would throw. saveQuietly() keeps observers and audit hooks out of a maintenance rewrite.

Know what this does not buy you legally#

Deterministic ipcrypt is pseudonymisation. The mapping is reversible with the key, and the IPv4 space is 2^32 — small enough that anyone holding the key and a candidate list can build a lookup table in minutes. Under GDPR Recital 26, pseudonymised data that can be attributed to a person using additional information is still personal data, so retention limits, subject access requests and breach notification duties all still apply.

What it does buy you is real: a leaked database dump no longer hands over client addresses, an analyst querying the audit table never sees one, and the blast radius of a read-only SQL injection drops sharply. That is a meaningful control. It is not anonymisation, and if your retention policy says "we do not keep IP addresses", the honest implementation is still DELETE.

I am not a lawyer, and whether this satisfies a given regulator is a question for one. The technical claim you can defend is "pseudonymised with a key held outside the database", not "anonymised".

Wrapping Up#

Start with the deterministic variant, a 45-character column, one env var and the cast. That combination is a drop-in change to an existing audit table — same queries, same index, same grouping — and it takes the raw addresses off disk. Add _pfx_ later if someone needs subnet analytics, and reach for _nd_ only where unlinkability matters more than being able to query the column at all.

Before the upgrade itself, work through the PHP 8.6 checklist for Laravel apps, and make sure the key lands in whatever you use for production secrets management rather than in a .env file on a single box.

FAQ#

What is ipcrypt in PHP 8.6?

ipcrypt is a family of ciphers whose plaintext and ciphertext are both IP addresses, specified in the IETF Internet-Draft draft-denis-ipcrypt and implemented in libsodium 1.0.21. PHP 8.6 exposes twelve functions for it in ext-sodium, covering four modes: deterministic, non-deterministic (_nd_), extended non-deterministic (_ndx_) and prefix-preserving (_pfx_). The deterministic and prefix-preserving modes return a valid IP address, so a column typed for addresses keeps working unchanged.

How do I pseudonymise IP addresses in Laravel?

Add a custom Eloquent cast implementing CastsAttributes whose set() calls sodium_crypto_ipcrypt_encrypt() and whose get() calls sodium_crypto_ipcrypt_decrypt(), then attach it to the IP column in the model's casts() method. Store the key in its own environment variable rather than deriving it from APP_KEY. Add a middleware that writes the pseudonymised address into the request context, so logs and exception reports pick up the pseudonym instead of the real address.

Is encrypting an IP address enough for GDPR?

No. Deterministic ipcrypt is pseudonymisation, not anonymisation — the original address is recoverable with the key, and GDPR Recital 26 treats data that can be re-attributed using additional information as personal data. Retention limits, subject access obligations and breach notification duties are unchanged. It is a genuine security control that reduces exposure from a leaked dump or a read-only injection, but it does not take the column outside the regulation.

What is the difference between deterministic and prefix-preserving ipcrypt?

Deterministic mode (sodium_crypto_ipcrypt_encrypt()) maps each address to a single fixed output, so equality and grouping work, but subnet structure is destroyed — two addresses in the same /24 encrypt to unrelated outputs. Prefix-preserving mode (sodium_crypto_ipcrypt_pfx_encrypt()) keeps shared prefixes shared, so /24-level analytics still work, and it preserves the address family as well. That preservation is a deliberate information leak, so pick _pfx_ only when subnet-level aggregation is a requirement.

How do I store an encrypted IP address in a database column?

Use a 45-character string column, or inet on PostgreSQL. Deterministic ipcrypt encrypts the 16-byte representation of the address, so an IPv4 input generally comes back formatted as IPv6 — a varchar(15) column sized for IPv4 will truncate it. If you prefer fixed-width binary storage, use sodium_ip2bin() to get the 16-byte form and put that in a binary(16), converting back with sodium_bin2ip(). The _nd_ and _ndx_ variants return 48 and 64 hex characters instead and need their own column type.

Does ipcrypt work with IPv6?

Yes. All four variants accept IPv4 and IPv6 input, because the underlying primitive operates on the 16-byte representation and IPv4 addresses are handled as IPv4-mapped IPv6 internally. Deterministic and _nd_/_ndx_ modes round-trip IPv6 exactly; prefix-preserving mode additionally returns IPv6 output for IPv6 input and IPv4 output for IPv4 input. Passing anything that is not a valid address throws a SodiumException rather than returning false.

Steven Richardson
Steven Richardson

CTO at Digitonic. Writing about Laravel, architecture, and the craft of leading software teams from the west coast of Scotland.