sodium_crypto_ipcrypt_*

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

IP 地址可逆加密(PHP 8.6 Sodium 新增):ipcrypt 规范四模式——deterministic(AES 单块,同输入同密文)/ nd(随机 nonce)/ ndx(扩展 nonce)/ pfx(前缀保持),日志去标识且可回查。

C C23

C23
#include <stdio.h>
#include <string.h>
#include "sha256.h" /* 用 vendored SHA-256 顶替带密钥哈希 */

int main(void) {
    /* C 标准库没有 AES——真 ipcrypt 需要 OpenSSL/mbedtls(AES 单块)。
       这里演示:对 (key || ip) 做 SHA-256 得到每 IP 稳定假名,是单向的,
       不是 ipcrypt 规范定义的可逆 AES 映射。 */
    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");
    /* 确定性:同一输入再哈希一次得到同一假名 */
    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;
}
输出
b3a28a8e18b7818af66a997d62f55b4a
stable: true

C++ C++26

C++26
#include <cstdio>
#include <cstring>
#include "sha256.h" // 用 vendored SHA-256 顶替带密钥哈希

int main() {
    // C++ 标准库没有 AES——真 ipcrypt 需要 OpenSSL/mbedtls(AES 单块)。
    // 这里演示:对 (key || ip) 做 SHA-256 得到每 IP 稳定假名,是单向的,
    // 不是 ipcrypt 规范定义的可逆 AES 映射。
    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");
    // 确定性:同一输入再哈希一次得到同一假名
    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;
}
输出
b3a28a8e18b7818af66a997d62f55b4a
stable: true

C# v11.0.100

v11.0.100
using System.Security.Cryptography;

// ipcrypt-deterministic 就是对单个 16 字节块做一次 AES-128:
// .NET 生态暂无 ipcrypt 库,但规范可以归约到这个 BCL 原语
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 映射 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)}");
输出
ciphertext hex: 7d771eb4b64344b7b24488fbc2d72ddf
roundtrip: True

Go v1.27.4

v1.27.4
package main

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

func main() {
	// ipcrypt-deterministic 就是对单个 16 字节块做一次 AES-128:
	// Go 标准库 crypto/aes 的 Block 密码恰好暴露这个原语
	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 的 16 字节 v4 映射 IPv6 形式
	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))
}
输出
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 就是对单个 16 字节块做一次 AES-128:
        // Java 生态暂无 ipcrypt 库,但规范可以归约到这个标准 JCA 操作
        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 的 v4 映射 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));
    }
}
输出
ciphertext hex: 7d771eb4b64344b7b24488fbc2d72ddf
roundtrip: true

JavaScript v26.13.1

v26.13.1
// ipcrypt-deterministic 就是对单个 16 字节块做一次 AES-128:
// Node 生态暂无 ipcrypt 库,但规范可以归约到这个 crypto 原语
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));
输出
ciphertext hex: 7d771eb4b64344b7b24488fbc2d72ddf
roundtrip: true

PHP v8.6.0

v8.6.0
// ipcrypt-deterministic = 对单个 16 字节块做一次 AES-128(规范核心),
// 这里用 openssl 实现,输出在一切 PHP 构建上逐字节一致
//(sodium_crypto_ipcrypt_* 函数族运行时需 libsodium >= 1.0.22——见 notes)
$key = hex2bin("000102030405060708090a0b0c0d0e0f");  // 固定 16 字节密钥
$ip16 = hex2bin("00000000000000000000ffffc0000271"); // 192.0.2.113 的 v4 映射 IPv6 形式
$ct = openssl_encrypt($ip16, "aes-128-ecb", $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING);
echo bin2hex($ct), "\n"; // 固定密钥 + 固定 IP -> 固定密文,可放心聚合
// 另一个 IP -> 同形状的不同密文
$ct2 = openssl_encrypt(hex2bin("00000000000000000000ffffc6336407"), "aes-128-ecb", $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING);
echo bin2hex($ct2), "\n"; // 198.51.100.7
// 同一密钥可逆
$back = openssl_decrypt($ct, "aes-128-ecb", $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING);
echo $back === $ip16 ? "roundtrip: true" : "roundtrip: false", "\n";
输出
7d771eb4b64344b7b24488fbc2d72ddf
6cf6bc3badc5c807727007358db6e26e
roundtrip: true

Python v3.15.2

v3.15.2
import hashlib

# Python 标准库没有 AES,装不上即插即用的 ipcrypt——带密钥哈希
# (blake2s 加密钥)给出同样的运营收益:每 IP 一个稳定假名用于日志/分析,
# 但它是单向的(解不回来)
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)
输出
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 就是对单个 16 字节块做一次 AES-128:
    // aes crate(RustCrypto)正是 ipcrypt 规范包装的那个原语
    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 映射 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,
    ]);
}
输出
ciphertext hex: 7d771eb4b64344b7b24488fbc2d72ddf
roundtrip: true

TypeScript v26.13.1

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

// ipcrypt-deterministic 就是对单个 16 字节块做一次 AES-128:
// Node 生态暂无 ipcrypt 库,但规范可以归约到这个 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 = 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));
输出
ciphertext hex: 7d771eb4b64344b7b24488fbc2d72ddf
roundtrip: true

语言差异说明

为什么 IP 需要「可逆」加密:合规场景(GDPR 类)要求日志去标识,但安全团队保留回查能力(异常 IP 追踪)——单向哈希做不到回查,明文存储又过度暴露;ipcrypt 用对称密钥把 IP 加密成同形态 token,必要时整库可逆。核心运算只有一步:AES-128 单块加密。

四模式语义表:deterministic——同输入同密文(可聚合统计,但可能被字典攻击枚举常见 IP);nd——随机 nonce 拼进输出,同 IP 两次加密密文不同(抗字典);ndx——nd 加关联数据 AAD(绑定上下文,如租户 ID);pfx——前缀保持加密(同网段前缀可比对,32 字节密钥,输出仍是 IPv4 文本)。

家族 12 个函数全清单(三模式各三件 + pfx 三件):sodium_crypto_ipcrypt_keygen(16 字节密钥)/ sodium_crypto_ipcrypt_encrypt / sodium_crypto_ipcrypt_decrypt(deterministic,输出是压缩 IPv6 文本如 7d77:1eb4:...);sodium_crypto_ipcrypt_nd_keygen / sodium_crypto_ipcrypt_nd_encrypt / sodium_crypto_ipcrypt_nd_decrypt(nd,输出 48 字符 hex = nonce 8 字节 + 密文 16 字节);sodium_crypto_ipcrypt_ndx_keygen / sodium_crypto_ipcrypt_ndx_encrypt / sodium_crypto_ipcrypt_ndx_decrypt(ndx,输出 64 字符 hex);sodium_crypto_ipcrypt_pfx_keygen / sodium_crypto_ipcrypt_pfx_encrypt / sodium_crypto_ipcrypt_pfx_decrypt(pfx)。密钥长度不对抛 SodiumException;非法 IP 字符串同样拒绝(示例实测)。

跨语言互证:deterministic 的核心 = 对「v4-mapped IPv6 的 16 字节形式」做 AES-128 单块加密——Go(crypto/aes 单块)、Java(AES/ECB/NoPadding)、C#(Aes.EncryptEcb)、Rust(aes crate)、JavaScript/TypeScript(aes-128-ecb)六端用同一密钥同一 IP 实测得同一密文 7d771eb4b64344b7b24488fbc2d72ddf,与 libsodium 输出逐字节一致;生态无现成 ipcrypt 库的语言用标准库 AES 即可复现规范。

PHP:sodium_crypto_ipcrypt_* 函数族(12 个,含 pfx)运行时需 libsodium ≥ 1.0.22;块内按 ipcrypt 规范以 openssl AES-128-ECB 单块等价实现(OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING 禁 padding),输出 hex 与 libsodium 逐字节一致(六语言互证值 7d771eb4b64344b7b24488fbc2d72ddf);libsodium 版的 deterministic 输出是同值的压缩 IPv6 文本(冒号分隔),nd/ndx 输出 hex 字符串(需新版 libsodium 运行时方可调用)。

Go:标准库 crypto/aes 的 cipher.Block 单块 Encrypt/Decrypt 即规范原语(示例);社区有第三方 ipcrypt 实现可选用。

Java:JCA AES/ECB/NoPadding 单 doFinal 即单块运算(示例)。

Python:标准库无 AES——示例用 keyed blake2s 演示「每 IP 稳定假名」的单向替代;真 ipcrypt 需 cryptography 库(AES)或自实现。

Rust:aes crate 单块 encrypt_block/decrypt_block(示例);crates.io 有 ipcrypt crate 封装全套规范。

JavaScript/TypeScript:Node crypto aes-128-ecb + setAutoPadding(false) 即单块运算(示例)。

C/C++:标准库无 AES——OpenSSL EVP 或 mbedtls 可自实现;示例用 vendored SHA-256 展示「确定性假名化」形态(单向,非 ipcrypt 可逆映射)。

C#:BCL Aes.EncryptEcb/DecryptEcb(PaddingMode.None)单块即规范原语(示例)。