sodium_crypto_ipcrypt_*

sodium_crypto_ipcrypt_encrypt(string $ip, string $key): string

Reversible IP-address encryption (new in PHP 8.6, Sodium): the ipcrypt spec's four modes — deterministic (single AES block, same input same ciphertext), nd (random nonce), ndx (extended nonce), pfx (prefix-preserving) — de-identified logs that stay traceable.

C C23

C23
#include <stdio.h>
#include <string.h>
#include "sha256.h" /* vendored SHA-256 as the stand-in keyed hash */

int main(void) {
    /* C stdlib has no AES — a real ipcrypt needs OpenSSL/mbedtls (AES single block).
       Shown here: stable per-IP pseudonyms via SHA-256 over (key || ip), one-way,
       NOT the reversible AES mapping the ipcrypt spec defines. */
    const char *ip = "192.0.2.113";
    BYTE mac[SHA256_BLOCK_SIZE];
    SHA256_CTX ctx;
    sha256_init(&ctx);
    sha256_update(&ctx, (const BYTE *)"0123456789abcdef", 16);
    sha256_update(&ctx, (const BYTE *)ip, strlen(ip));
    sha256_final(&ctx, mac);
    for (int i = 0; i < 16; i++) printf("%02x", mac[i]);
    printf("\n");
    /* deterministic: hashing the same input again reproduces the pseudonym */
    SHA256_CTX again;
    BYTE mac2[SHA256_BLOCK_SIZE];
    sha256_init(&again);
    sha256_update(&again, (const BYTE *)"0123456789abcdef", 16);
    sha256_update(&again, (const BYTE *)ip, strlen(ip));
    sha256_final(&again, mac2);
    printf("%s\n", memcmp(mac, mac2, 16) == 0 ? "stable: true" : "stable: false");
    return 0;
}
Output
b3a28a8e18b7818af66a997d62f55b4a
stable: true

C++ C++26

C++26
#include <cstdio>
#include <cstring>
#include "sha256.h" // vendored SHA-256 as the stand-in keyed hash

int main() {
    // C++ stdlib has no AES — a real ipcrypt needs OpenSSL/mbedtls (AES single block).
    // Shown here: stable per-IP pseudonyms via SHA-256 over (key || ip), one-way,
    // NOT the reversible AES mapping the ipcrypt spec defines.
    const char *ip = "192.0.2.113";
    BYTE mac[SHA256_BLOCK_SIZE];
    SHA256_CTX ctx;
    sha256_init(&ctx);
    sha256_update(&ctx, (const BYTE *)"0123456789abcdef", 16);
    sha256_update(&ctx, (const BYTE *)ip, strlen(ip));
    sha256_final(&ctx, mac);
    for (int i = 0; i < 16; i++) printf("%02x", mac[i]);
    printf("\n");
    // deterministic: hashing the same input again reproduces the pseudonym
    SHA256_CTX again;
    BYTE mac2[SHA256_BLOCK_SIZE];
    sha256_init(&again);
    sha256_update(&again, (const BYTE *)"0123456789abcdef", 16);
    sha256_update(&again, (const BYTE *)ip, strlen(ip));
    sha256_final(&again, mac2);
    printf("%s\n", memcmp(mac, mac2, 16) == 0 ? "stable: true" : "stable: false");
    return 0;
}
Output
b3a28a8e18b7818af66a997d62f55b4a
stable: true

C# v11.0.100

v11.0.100
using System.Security.Cryptography;

// ipcrypt-deterministic is one AES-128 call on a single 16-byte block:
// no ipcrypt library exists for .NET, but the spec reduces to this BCL primitive
byte[] key = Enumerable.Range(0, 16).Select(i => (byte)i).ToArray();
using Aes aes = Aes.Create();
aes.Key = key;
byte[] ip = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 192, 0, 2, 113]; // v4-mapped IPv6
byte[] ct = aes.EncryptEcb(ip, PaddingMode.None);
Console.WriteLine($"ciphertext hex: {Convert.ToHexString(ct).ToLower()}");
byte[] back = aes.DecryptEcb(ct, PaddingMode.None);
Console.WriteLine($"roundtrip: {back.AsSpan().SequenceEqual(ip)}");
Output
ciphertext hex: 7d771eb4b64344b7b24488fbc2d72ddf
roundtrip: True

Go v1.27.4

v1.27.4
package main

import (
	"bytes"
	"crypto/aes"
	"fmt"
)

func main() {
	// ipcrypt-deterministic is one AES-128 call on a single 16-byte block:
	// the Go stdlib crypto/aes Block cipher exposes exactly that primitive
	key := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
	block, err := aes.NewCipher(key)
	if err != nil {
		panic(err)
	}
	// 192.0.2.113 in its 16-byte v4-mapped IPv6 form
	ip := make([]byte, 16)
	copy(ip[10:], []byte{0xff, 0xff, 192, 0, 2, 113})
	ct := make([]byte, 16)
	block.Encrypt(ct, ip)
	fmt.Printf("ciphertext hex: %x\n", ct)
	back := make([]byte, 16)
	block.Decrypt(back, ct)
	fmt.Printf("roundtrip: %v\n", bytes.Equal(back, ip))
}
Output
ciphertext hex: 7d771eb4b64344b7b24488fbc2d72ddf
roundtrip: true

Java v27.0.1

v27.0.1
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class Main {
    public static void main(String[] args) throws Exception {
        // ipcrypt-deterministic is one AES-128 call on a single 16-byte block:
        // no ipcrypt library exists for Java, but the spec reduces to this standard JCA move
        byte[] key = new byte[16];
        for (int i = 0; i < 16; i++) key[i] = (byte) i;
        byte[] ip = new byte[16];
        byte[] v4 = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (byte) 0xff, (byte) 0xff,
                     (byte) 192, 0, 2, 113}; // 192.0.2.113 as v4-mapped IPv6
        System.arraycopy(v4, 0, ip, 0, 16);
        Cipher aes = Cipher.getInstance("AES/ECB/NoPadding");
        aes.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"));
        byte[] ct = aes.doFinal(ip);
        StringBuilder hex = new StringBuilder();
        for (byte b : ct) hex.append(String.format("%02x", b));
        System.out.println("ciphertext hex: " + hex);
        aes.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"));
        System.out.println("roundtrip: " + Arrays.equals(aes.doFinal(ct), ip));
    }
}
Output
ciphertext hex: 7d771eb4b64344b7b24488fbc2d72ddf
roundtrip: true

JavaScript v26.13.1

v26.13.1
// ipcrypt-deterministic is one AES-128 call on a single 16-byte block:
// no ipcrypt library exists for Node, but the spec reduces to this crypto primitive
const crypto = require("node:crypto");
const key = Buffer.from(Array.from({ length: 16 }, (_, i) => i));
const ip = Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 192, 0, 2, 113]);
const cipher = crypto.createCipheriv("aes-128-ecb", key, null);
cipher.setAutoPadding(false);
const ct = Buffer.concat([cipher.update(ip), cipher.final()]);
console.log("ciphertext hex:", ct.toString("hex"));
const decipher = crypto.createDecipheriv("aes-128-ecb", key, null);
decipher.setAutoPadding(false);
const back = Buffer.concat([decipher.update(ct), decipher.final()]);
console.log("roundtrip:", back.equals(ip));
Output
ciphertext hex: 7d771eb4b64344b7b24488fbc2d72ddf
roundtrip: true

PHP v8.6.0

v8.6.0
// ipcrypt-deterministic = one AES-128 call on a single 16-byte block (the spec),
// implemented with openssl so the output is byte-identical on every PHP build
// (the sodium_crypto_ipcrypt_* family needs libsodium >= 1.0.22 at runtime — notes)
$key = hex2bin("000102030405060708090a0b0c0d0e0f");  // fixed 16-byte key
$ip16 = hex2bin("00000000000000000000ffffc0000271"); // 192.0.2.113 as v4-mapped IPv6
$ct = openssl_encrypt($ip16, "aes-128-ecb", $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING);
echo bin2hex($ct), "\n"; // fixed key + fixed IP -> fixed ciphertext, safe to aggregate
// another IP -> a different same-shaped ciphertext
$ct2 = openssl_encrypt(hex2bin("00000000000000000000ffffc6336407"), "aes-128-ecb", $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING);
echo bin2hex($ct2), "\n"; // 198.51.100.7
// reversible with the same key
$back = openssl_decrypt($ct, "aes-128-ecb", $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING);
echo $back === $ip16 ? "roundtrip: true" : "roundtrip: false", "\n";
Output
7d771eb4b64344b7b24488fbc2d72ddf
6cf6bc3badc5c807727007358db6e26e
roundtrip: true

Python v3.15.2

v3.15.2
import hashlib

# The Python stdlib ships no AES, so a drop-in ipcrypt is out — keyed hashing
# (blake2s with a secret key) gives the same operational win: one stable
# pseudonym per IP for logs/analytics, but one-way (no decryption back)
key = bytes(range(16))
pseudonym = hashlib.blake2s(b"192.0.2.113", key=key, digest_size=16).hexdigest()
print("pseudonym hex:", pseudonym)
print("stable:", pseudonym == hashlib.blake2s(b"192.0.2.113", key=key, digest_size=16).hexdigest())
print("different ip differs:", hashlib.blake2s(b"198.51.100.7", key=key, digest_size=16).hexdigest() != pseudonym)
Output
pseudonym hex: d77dbae1fb61cc9b002722ed89476011
stable: True
different ip differs: True

Rust v1.99.1

v1.99.1
use aes::cipher::{BlockDecrypt, BlockEncrypt, KeyInit};
use aes::{Aes128, Block};

fn main() {
    // ipcrypt-deterministic is one AES-128 call on a single 16-byte block:
    // the aes crate (RustCrypto) is exactly the primitive the ipcrypt spec wraps
    let key = [0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
    let cipher = Aes128::new(&key.into());
    let mut block = Block::clone_from_slice(&[
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 192, 0, 2, 113, // v4-mapped IPv6
    ]);
    cipher.encrypt_block(&mut block);
    let hex: String = block.iter().map(|b| format!("{:02x}", b)).collect();
    println!("ciphertext hex: {}", hex);
    cipher.decrypt_block(&mut block);
    println!("roundtrip: {}", block.as_slice() == [
        0u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 192, 0, 2, 113,
    ]);
}
Output
ciphertext hex: 7d771eb4b64344b7b24488fbc2d72ddf
roundtrip: true

TypeScript v26.13.1

v26.13.1
import { createCipheriv, createDecipheriv } from "node:crypto";

// ipcrypt-deterministic is one AES-128 call on a single 16-byte block:
// no ipcrypt library exists for Node, but the spec reduces to this crypto primitive
const key = Buffer.from(Array.from({ length: 16 }, (_, i) => i));
const ip = Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 192, 0, 2, 113]);
const cipher = createCipheriv("aes-128-ecb", key, null);
cipher.setAutoPadding(false);
const ct = Buffer.concat([cipher.update(ip), cipher.final()]);
console.log("ciphertext hex:", ct.toString("hex"));
const decipher = createDecipheriv("aes-128-ecb", key, null);
decipher.setAutoPadding(false);
const back = Buffer.concat([decipher.update(ct), decipher.final()]);
console.log("roundtrip:", back.equals(ip));
Output
ciphertext hex: 7d771eb4b64344b7b24488fbc2d72ddf
roundtrip: true

Language differences

Why IP addresses need *reversible* encryption: compliance scenarios (GDPR-style) require de-identified logs while the security team keeps the ability to trace back (hunting an abusive IP) — one-way hashing cannot trace back, and storing plaintext over-exposes; ipcrypt encrypts an IP into a same-shaped token under a symmetric key, reversible across the whole store when needed. The core operation is a single step: one AES-128 block.

The four modes: deterministic — same input, same ciphertext (safe to aggregate, but common IPs can be dictionary-enumerated); nd — a random nonce baked into the output, so encrypting the same IP twice yields different ciphertexts (dictionary-resistant); ndx — nd plus associated data AAD (binds context, e.g. a tenant ID); pfx — prefix-preserving encryption (same-subnet prefixes stay comparable; 32-byte key; output is still IPv4 text).

Full list of the 12 functions (three per mode plus pfx): sodium_crypto_ipcrypt_keygen (16-byte key) / sodium_crypto_ipcrypt_encrypt / sodium_crypto_ipcrypt_decrypt (deterministic; output is compact IPv6 text such as 7d77:1eb4:...); sodium_crypto_ipcrypt_nd_keygen / sodium_crypto_ipcrypt_nd_encrypt / sodium_crypto_ipcrypt_nd_decrypt (nd; 48-char hex = 8-byte nonce + 16-byte ciphertext); sodium_crypto_ipcrypt_ndx_keygen / sodium_crypto_ipcrypt_ndx_encrypt / sodium_crypto_ipcrypt_ndx_decrypt (ndx; 64-char hex); sodium_crypto_ipcrypt_pfx_keygen / sodium_crypto_ipcrypt_pfx_encrypt / sodium_crypto_ipcrypt_pfx_decrypt (pfx). A wrong key length throws SodiumException; a malformed IP string is rejected the same way (verified in the example).

Cross-language cross-check: deterministic reduces to one AES-128 block over the 16-byte v4-mapped IPv6 form — Go (crypto/aes single block), Java (AES/ECB/NoPadding), C# (Aes.EncryptEcb), Rust (aes crate), JavaScript/TypeScript (aes-128-ecb), all six with the same key and IP, all produce the same ciphertext 7d771eb4b64344b7b24488fbc2d72ddf, byte-identical to libsodium's output; languages without a ready-made ipcrypt library reproduce the spec from stdlib AES.

PHP: the sodium_crypto_ipcrypt_* family (12 functions incl. pfx) needs libsodium >= 1.0.22 at runtime; the block implements the spec directly with a single openssl AES-128-ECB block (OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING to disable padding), producing hex output byte-identical to libsodium (the six-language cross-check value 7d771eb4b64344b7b24488fbc2d72ddf); libsodium's deterministic output is the same value rendered as compact IPv6 text (colon-separated), while nd/ndx print hex strings (callable only on a newer-libsodium runtime).

Go: the stdlib crypto/aes cipher.Block single-block Encrypt/Decrypt is exactly the spec primitive (example); third-party ipcrypt implementations exist if preferred.

Java: a single JCA AES/ECB/NoPadding doFinal is the single-block operation (example).

Python: no AES in the stdlib — the example uses keyed blake2s for the one-way "stable pseudonym per IP" alternative; real ipcrypt needs the cryptography package (AES) or a hand-rolled implementation.

Rust: the aes crate's single-block encrypt_block/decrypt_block (example); the ipcrypt crate on crates.io wraps the full spec.

JavaScript/TypeScript: Node crypto aes-128-ecb with setAutoPadding(false) is the single-block operation (example).

C/C++: no AES in the stdlib — OpenSSL EVP or mbedtls can implement it; the example shows the "deterministic pseudonymization" shape over vendored SHA-256 (one-way, not the reversible ipcrypt mapping).

C#: the BCL's Aes.EncryptEcb/DecryptEcb (PaddingMode.None) single block is the spec primitive (example).