openssl_encrypt

openssl_encrypt(string $data, string $cipher_algo, string $passphrase, int $options = 0, string $iv = "", string &$tag = null, string $aad = "", int $tag_length = 16): string|false

用 AES-256-GCM 做带认证加密:openssl_encrypt 的 tag/aad 参数演示,$passphrase 实为原始密钥,验签失败 openssl_decrypt 返回 false。

C C23

C23
#include <stdio.h>
#include <string.h>
#include <stdint.h>

// 纯 C 手写 AES-256-GCM,教学向实现。
// 生产环境用 OpenSSL EVP_aes_256_gcm;这里展开内部结构。

static const uint8_t SBOX[256] = {
    0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
    0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
    0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15,
    0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75,
    0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84,
    0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf,
    0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8,
    0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2,
    0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73,
    0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb,
    0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79,
    0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08,
    0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a,
    0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e,
    0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf,
    0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16
};

static uint8_t xtime(uint8_t a) {
    return (uint8_t)((a << 1) ^ ((a & 0x80) ? 0x1b : 0));
}

static uint8_t gmul(uint8_t a, uint8_t b) {
    uint8_t out = 0;
    while (b) {
        if (b & 1) out ^= a;
        a = xtime(a);
        b >>= 1;
    }
    return out;
}

// AES-256 密钥扩展:15 轮轮密钥共 240 字节存入 rk
static void aes256_key_expand(const uint8_t key[32], uint8_t rk[240]) {
    static const uint8_t RCON[11] = {0, 1, 2, 4, 8, 16, 32, 64, 128, 0x1b, 0x36};
    memcpy(rk, key, 32);
    for (int i = 32; i < 240; i += 4) {
        uint8_t t[4] = {rk[i - 4], rk[i - 3], rk[i - 2], rk[i - 1]};
        if (i % 32 == 0) {
            uint8_t tmp = t[0];
            t[0] = (uint8_t)(SBOX[t[1]] ^ RCON[i / 32]);
            t[1] = SBOX[t[2]];
            t[2] = SBOX[t[3]];
            t[3] = SBOX[tmp];
        } else if (i % 32 == 16) {
            for (int j = 0; j < 4; j++) t[j] = SBOX[t[j]];
        }
        for (int j = 0; j < 4; j++) rk[i + j] = (uint8_t)(rk[i - 32 + j] ^ t[j]);
    }
}

static void aes256_encrypt_block(const uint8_t rk[240], const uint8_t in[16], uint8_t out[16]) {
    uint8_t s[16];
    memcpy(s, in, 16);
#define ADD_RK(rnd) do { for (int i = 0; i < 16; i++) s[i] ^= rk[(rnd) * 16 + i]; } while (0)
#define SUB_BYTES() do { for (int i = 0; i < 16; i++) s[i] = SBOX[s[i]]; } while (0)
#define SHIFT_ROWS() do { \
    uint8_t t[16]; \
    memcpy(t, s, 16); \
    for (int r = 1; r < 4; r++) { \
        for (int c = 0; c < 4; c++) s[4 * c + r] = t[4 * ((c + r) % 4) + r]; \
    } \
} while (0)
#define MIX_COLUMNS() do { \
    for (int c = 0; c < 4; c++) { \
        uint8_t a0 = s[4 * c], a1 = s[4 * c + 1], a2 = s[4 * c + 2], a3 = s[4 * c + 3]; \
        s[4 * c]     = (uint8_t)(gmul(a0, 2) ^ gmul(a1, 3) ^ a2 ^ a3); \
        s[4 * c + 1] = (uint8_t)(a0 ^ gmul(a1, 2) ^ gmul(a2, 3) ^ a3); \
        s[4 * c + 2] = (uint8_t)(a0 ^ a1 ^ gmul(a2, 2) ^ gmul(a3, 3)); \
        s[4 * c + 3] = (uint8_t)(gmul(a0, 3) ^ a1 ^ a2 ^ gmul(a3, 2)); \
    } \
} while (0)
    ADD_RK(0);
    for (int rnd = 1; rnd < 14; rnd++) {
        SUB_BYTES();
        SHIFT_ROWS();
        MIX_COLUMNS();
        ADD_RK(rnd);
    }
    SUB_BYTES();
    SHIFT_ROWS();
    ADD_RK(14);
    memcpy(out, s, 16);
#undef ADD_RK
#undef SUB_BYTES
#undef SHIFT_ROWS
#undef MIX_COLUMNS
}

// GHASH 乘法:GF(2^128),位反转表示的 GCM 多项式
static unsigned __int128 gf_mul_gcm(unsigned __int128 x, unsigned __int128 y) {
    unsigned __int128 z = 0;
    const unsigned __int128 R = ((unsigned __int128)0xe1) << 120;
    for (int i = 127; i >= 0; i--) {
        if ((y >> i) & 1) z ^= x;
        x = (x >> 1) ^ ((x & 1) ? R : 0);
    }
    return z;
}

static unsigned __int128 ghash_block(unsigned __int128 h, unsigned __int128 x, const uint8_t *block, size_t n) {
    uint8_t buf[16] = {0};
    memcpy(buf, block, n);
    unsigned __int128 v = 0;
    memcpy((uint8_t *)&v + (16 - 16), buf, 16); // big-endian load via byte copy
    v = 0;
    for (int i = 0; i < 16; i++) v = (v << 8) | buf[i];
    return gf_mul_gcm(x ^ v, h);
}


int main(void) {
    const uint8_t key[32] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
                             16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31};
    const uint8_t iv[12] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
    const uint8_t aad[] = "header-v1";
    const uint8_t pt[] = "top secret payload";
    size_t mlen = strlen((const char *)pt);
    size_t aadlen = strlen((const char *)aad);

    uint8_t rk[240];
    aes256_key_expand(key, rk);

    uint8_t h[16], j0[16];
    aes256_encrypt_block(rk, (const uint8_t *)"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", h);
    memset(j0, 0, 16);
    memcpy(j0, iv, 12);
    j0[15] = 1;

    // CTR 加密:密钥流来自 E(iv || 计数器),计数器从 2 开始
    uint8_t ct[64];
    uint32_t counter = 2;
    for (size_t off = 0; off < mlen; off += 16) {
        uint8_t block[16];
        memcpy(block, iv, 12);
        block[12] = (uint8_t)(counter >> 24);
        block[13] = (uint8_t)(counter >> 16);
        block[14] = (uint8_t)(counter >> 8);
        block[15] = (uint8_t)counter;
        uint8_t ks[16];
        aes256_encrypt_block(rk, block, ks);
        size_t n = mlen - off < 16 ? mlen - off : 16;
        for (size_t i = 0; i < n; i++) ct[off + i] = pt[off + i] ^ ks[i];
        counter++;
    }

    // GHASH 输入:aad || ct || 两段比特长度,各段分别补零到整块
    unsigned __int128 hh = 0, x = 0;
    for (int i = 0; i < 16; i++) hh = (hh << 8) | h[i];
    x = ghash_block(hh, x, aad, aadlen);
    for (size_t off = 0; off < mlen; off += 16) {
        size_t n = mlen - off < 16 ? mlen - off : 16;
        x = ghash_block(hh, x, ct + off, n);
    }
    uint8_t lenblock[16] = {0};
    uint64_t abits = aadlen * 8, cbits = mlen * 8;
    for (int i = 0; i < 8; i++) lenblock[i] = (uint8_t)(abits >> (56 - 8 * i));
    for (int i = 0; i < 8; i++) lenblock[8 + i] = (uint8_t)(cbits >> (56 - 8 * i));
    x = ghash_block(hh, x, lenblock, 16);

    uint8_t s0[16], tag[16];
    aes256_encrypt_block(rk, j0, s0);
    for (int i = 0; i < 16; i++) {
        unsigned __int128 bytev = (x >> (8 * (15 - i))) & 0xff;
        tag[i] = (uint8_t)(bytev ^ s0[i]);
    }

    printf("gcm ct+tag: ");
    for (size_t i = 0; i < mlen; i++) printf("%02x", ct[i]);
    for (int i = 0; i < 16; i++) printf("%02x", tag[i]);
    printf("\n");
    // 解密回读:先重算 tag 比对再放出明文
    unsigned __int128 x2 = 0;
    x2 = ghash_block(hh, x2, aad, aadlen);
    for (size_t off = 0; off < mlen; off += 16) {
        size_t n = mlen - off < 16 ? mlen - off : 16;
        x2 = ghash_block(hh, x2, ct + off, n);
    }
    x2 = ghash_block(hh, x2, lenblock, 16);
    int ok = 1;
    for (int i = 0; i < 16; i++) {
        unsigned __int128 bytev = (x2 >> (8 * (15 - i))) & 0xff;
        if ((uint8_t)(bytev ^ s0[i]) != tag[i]) ok = 0;
    }
    printf("roundtrip: %s\n", ok ? "true" : "false");
    tag[0] ^= 1; // 翻转一个 tag 位:重算的 GHASH 不再匹配
    unsigned __int128 x3 = 0;
    x3 = ghash_block(hh, x3, aad, aadlen);
    for (size_t off = 0; off < mlen; off += 16) {
        size_t n = mlen - off < 16 ? mlen - off : 16;
        x3 = ghash_block(hh, x3, ct + off, n);
    }
    x3 = ghash_block(hh, x3, lenblock, 16);
    ok = 1;
    for (int i = 0; i < 16; i++) {
        unsigned __int128 bytev = (x3 >> (8 * (15 - i))) & 0xff;
        if ((uint8_t)(bytev ^ s0[i]) != tag[i]) ok = 0;
    }
    printf("bad tag decrypt: %s\n", ok ? "ok" : "auth failed");
    return 0;
}
输出
gcm ct+tag: 336da63bb680a169e835b7fbd0901402e2b2152918ea3ccfd5fdf6e2162f405d9c18
roundtrip: true
bad tag decrypt: auth failed

C++ C++26

C++26
#include <cstdio>
#include <cstring>
#include <cstdint>

// 纯 C++ 手写 AES-256-GCM,教学向实现。
// 生产环境用 OpenSSL EVP_aes_256_gcm;这里展开内部结构。

static const uint8_t SBOX[256] = {
    0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
    0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
    0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15,
    0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75,
    0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84,
    0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf,
    0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8,
    0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2,
    0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73,
    0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb,
    0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79,
    0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08,
    0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a,
    0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e,
    0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf,
    0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16
};

static uint8_t xtime(uint8_t a) {
    return (uint8_t)((a << 1) ^ ((a & 0x80) ? 0x1b : 0));
}

static uint8_t gmul(uint8_t a, uint8_t b) {
    uint8_t out = 0;
    while (b) {
        if (b & 1) out ^= a;
        a = xtime(a);
        b >>= 1;
    }
    return out;
}

// AES-256 密钥扩展:15 轮轮密钥共 240 字节存入 rk
static void aes256_key_expand(const uint8_t key[32], uint8_t rk[240]) {
    static const uint8_t RCON[11] = {0, 1, 2, 4, 8, 16, 32, 64, 128, 0x1b, 0x36};
    memcpy(rk, key, 32);
    for (int i = 32; i < 240; i += 4) {
        uint8_t t[4] = {rk[i - 4], rk[i - 3], rk[i - 2], rk[i - 1]};
        if (i % 32 == 0) {
            uint8_t tmp = t[0];
            t[0] = (uint8_t)(SBOX[t[1]] ^ RCON[i / 32]);
            t[1] = SBOX[t[2]];
            t[2] = SBOX[t[3]];
            t[3] = SBOX[tmp];
        } else if (i % 32 == 16) {
            for (int j = 0; j < 4; j++) t[j] = SBOX[t[j]];
        }
        for (int j = 0; j < 4; j++) rk[i + j] = (uint8_t)(rk[i - 32 + j] ^ t[j]);
    }
}

static void aes256_encrypt_block(const uint8_t rk[240], const uint8_t in[16], uint8_t out[16]) {
    uint8_t s[16];
    memcpy(s, in, 16);
#define ADD_RK(rnd) do { for (int i = 0; i < 16; i++) s[i] ^= rk[(rnd) * 16 + i]; } while (0)
#define SUB_BYTES() do { for (int i = 0; i < 16; i++) s[i] = SBOX[s[i]]; } while (0)
#define SHIFT_ROWS() do { \
    uint8_t t[16]; \
    memcpy(t, s, 16); \
    for (int r = 1; r < 4; r++) { \
        for (int c = 0; c < 4; c++) s[4 * c + r] = t[4 * ((c + r) % 4) + r]; \
    } \
} while (0)
#define MIX_COLUMNS() do { \
    for (int c = 0; c < 4; c++) { \
        uint8_t a0 = s[4 * c], a1 = s[4 * c + 1], a2 = s[4 * c + 2], a3 = s[4 * c + 3]; \
        s[4 * c]     = (uint8_t)(gmul(a0, 2) ^ gmul(a1, 3) ^ a2 ^ a3); \
        s[4 * c + 1] = (uint8_t)(a0 ^ gmul(a1, 2) ^ gmul(a2, 3) ^ a3); \
        s[4 * c + 2] = (uint8_t)(a0 ^ a1 ^ gmul(a2, 2) ^ gmul(a3, 3)); \
        s[4 * c + 3] = (uint8_t)(gmul(a0, 3) ^ a1 ^ a2 ^ gmul(a3, 2)); \
    } \
} while (0)
    ADD_RK(0);
    for (int rnd = 1; rnd < 14; rnd++) {
        SUB_BYTES();
        SHIFT_ROWS();
        MIX_COLUMNS();
        ADD_RK(rnd);
    }
    SUB_BYTES();
    SHIFT_ROWS();
    ADD_RK(14);
    memcpy(out, s, 16);
#undef ADD_RK
#undef SUB_BYTES
#undef SHIFT_ROWS
#undef MIX_COLUMNS
}

// GHASH 乘法:GF(2^128),位反转表示的 GCM 多项式
static unsigned __int128 gf_mul_gcm(unsigned __int128 x, unsigned __int128 y) {
    unsigned __int128 z = 0;
    const unsigned __int128 R = ((unsigned __int128)0xe1) << 120;
    for (int i = 127; i >= 0; i--) {
        if ((y >> i) & 1) z ^= x;
        x = (x >> 1) ^ ((x & 1) ? R : 0);
    }
    return z;
}

static unsigned __int128 ghash_block(unsigned __int128 h, unsigned __int128 x, const uint8_t *block, size_t n) {
    uint8_t buf[16] = {0};
    memcpy(buf, block, n);
    unsigned __int128 v = 0;
    memcpy((uint8_t *)&v + (16 - 16), buf, 16); // big-endian load via byte copy
    v = 0;
    for (int i = 0; i < 16; i++) v = (v << 8) | buf[i];
    return gf_mul_gcm(x ^ v, h);
}


int main() {
    const uint8_t key[32] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
                             16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31};
    const uint8_t iv[12] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
    const uint8_t aad[] = "header-v1";
    const uint8_t pt[] = "top secret payload";
    size_t mlen = strlen((const char *)pt);
    size_t aadlen = strlen((const char *)aad);

    uint8_t rk[240];
    aes256_key_expand(key, rk);

    uint8_t h[16], j0[16];
    aes256_encrypt_block(rk, (const uint8_t *)"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", h);
    memset(j0, 0, 16);
    memcpy(j0, iv, 12);
    j0[15] = 1;

    // CTR 加密:密钥流来自 E(iv || 计数器),计数器从 2 开始
    uint8_t ct[64];
    uint32_t counter = 2;
    for (size_t off = 0; off < mlen; off += 16) {
        uint8_t block[16];
        memcpy(block, iv, 12);
        block[12] = (uint8_t)(counter >> 24);
        block[13] = (uint8_t)(counter >> 16);
        block[14] = (uint8_t)(counter >> 8);
        block[15] = (uint8_t)counter;
        uint8_t ks[16];
        aes256_encrypt_block(rk, block, ks);
        size_t n = mlen - off < 16 ? mlen - off : 16;
        for (size_t i = 0; i < n; i++) ct[off + i] = pt[off + i] ^ ks[i];
        counter++;
    }

    // GHASH 输入:aad || ct || 两段比特长度,各段分别补零到整块
    unsigned __int128 hh = 0, x = 0;
    for (int i = 0; i < 16; i++) hh = (hh << 8) | h[i];
    x = ghash_block(hh, x, aad, aadlen);
    for (size_t off = 0; off < mlen; off += 16) {
        size_t n = mlen - off < 16 ? mlen - off : 16;
        x = ghash_block(hh, x, ct + off, n);
    }
    uint8_t lenblock[16] = {0};
    uint64_t abits = aadlen * 8, cbits = mlen * 8;
    for (int i = 0; i < 8; i++) lenblock[i] = (uint8_t)(abits >> (56 - 8 * i));
    for (int i = 0; i < 8; i++) lenblock[8 + i] = (uint8_t)(cbits >> (56 - 8 * i));
    x = ghash_block(hh, x, lenblock, 16);

    uint8_t s0[16], tag[16];
    aes256_encrypt_block(rk, j0, s0);
    for (int i = 0; i < 16; i++) {
        unsigned __int128 bytev = (x >> (8 * (15 - i))) & 0xff;
        tag[i] = (uint8_t)(bytev ^ s0[i]);
    }

    printf("gcm ct+tag: ");
    for (size_t i = 0; i < mlen; i++) printf("%02x", ct[i]);
    for (int i = 0; i < 16; i++) printf("%02x", tag[i]);
    printf("\n");
    // 解密回读:先重算 tag 比对再放出明文
    unsigned __int128 x2 = 0;
    x2 = ghash_block(hh, x2, aad, aadlen);
    for (size_t off = 0; off < mlen; off += 16) {
        size_t n = mlen - off < 16 ? mlen - off : 16;
        x2 = ghash_block(hh, x2, ct + off, n);
    }
    x2 = ghash_block(hh, x2, lenblock, 16);
    int ok = 1;
    for (int i = 0; i < 16; i++) {
        unsigned __int128 bytev = (x2 >> (8 * (15 - i))) & 0xff;
        if ((uint8_t)(bytev ^ s0[i]) != tag[i]) ok = 0;
    }
    printf("roundtrip: %s\n", ok ? "true" : "false");
    tag[0] ^= 1; // 翻转一个 tag 位:重算的 GHASH 不再匹配
    unsigned __int128 x3 = 0;
    x3 = ghash_block(hh, x3, aad, aadlen);
    for (size_t off = 0; off < mlen; off += 16) {
        size_t n = mlen - off < 16 ? mlen - off : 16;
        x3 = ghash_block(hh, x3, ct + off, n);
    }
    x3 = ghash_block(hh, x3, lenblock, 16);
    ok = 1;
    for (int i = 0; i < 16; i++) {
        unsigned __int128 bytev = (x3 >> (8 * (15 - i))) & 0xff;
        if ((uint8_t)(bytev ^ s0[i]) != tag[i]) ok = 0;
    }
    printf("bad tag decrypt: %s\n", ok ? "ok" : "auth failed");
    return 0;
}
输出
gcm ct+tag: 336da63bb680a169e835b7fbd0901402e2b2152918ea3ccfd5fdf6e2162f405d9c18
roundtrip: true
bad tag decrypt: auth failed

C# v11.0.100

v11.0.100
using System;
using System.Linq;
using System.Security.Cryptography;

// AesGcm(.NET 5+)即 openssl_encrypt("aes-256-gcm") 的对照实现
byte[] key = Enumerable.Range(0, 32).Select(i => (byte)i).ToArray();
byte[] iv = Enumerable.Range(0, 12).Select(i => (byte)i).ToArray();
byte[] aad = System.Text.Encoding.ASCII.GetBytes("header-v1");
byte[] pt = System.Text.Encoding.ASCII.GetBytes("top secret payload");

byte[] ct = new byte[pt.Length];
byte[] tag = new byte[16]; // 对应 PHP 的 $tag 按引用参数
using (var gcm = new AesGcm(key, tag.Length)) {
    gcm.Encrypt(iv, pt, ct, tag, aad);
}
Console.WriteLine($"gcm ct+tag: {Convert.ToHexString(ct).ToLower()}{Convert.ToHexString(tag).ToLower()}");

byte[] back = new byte[pt.Length];
using (var gcm = new AesGcm(key, tag.Length)) {
    gcm.Decrypt(iv, ct, tag, back, aad);
}
bool ok = System.Text.Encoding.ASCII.GetString(back) == "top secret payload";
Console.WriteLine($"roundtrip: {(ok ? "true" : "false")}");

tag[0] ^= 1; // 篡改 tag
try {
    using var gcm2 = new AesGcm(key, tag.Length);
    gcm2.Decrypt(iv, ct, tag, back, aad);
    Console.WriteLine("bad tag decrypt: ok");
} catch (CryptographicException) {
    Console.WriteLine("bad tag decrypt: auth failed");
}
输出
gcm ct+tag: 336da63bb680a169e835b7fbd0901402e2b2152918ea3ccfd5fdf6e2162f405d9c18
roundtrip: true
bad tag decrypt: auth failed

Go v1.27.4

v1.27.4
package main

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/hex"
	"fmt"
)

func main() {
	key := new([32]byte) // 固定演示 key(生产:随机生成并保密)
	for i := range key {
		key[i] = byte(i)
	}
	block, err := aes.NewCipher(key[:])
	if err != nil {
		panic(err)
	}
	gcm, err := cipher.NewGCM(block) // 标准库 GCM:tag 默认 16 字节
	if err != nil {
		panic(err)
	}
	iv := make([]byte, 12) // 固定演示 IV(生产:每条消息随机)
	for i := range iv {
		iv[i] = byte(i)
	}
	aad := []byte("header-v1")
	pt := []byte("top secret payload")
	ct := gcm.Seal(nil, iv, pt, aad) // 密文 || tag 拼在一个切片里
	fmt.Println("gcm ct+tag:", hex.EncodeToString(ct))
	back, err := gcm.Open(nil, iv, ct, aad)
	fmt.Println("roundtrip:", err == nil && bytes.Equal(back, pt))
	badTag := bytes.Clone(ct)
	badTag[len(badTag)-1] ^= 1 // 翻转一个 tag 位
	_, err = gcm.Open(nil, iv, badTag, aad)
	if err != nil {
		fmt.Println("bad tag decrypt: auth failed")
	} else {
		fmt.Println("bad tag decrypt: ok")
	}
}
输出
gcm ct+tag: 336da63bb680a169e835b7fbd0901402e2b2152918ea3ccfd5fdf6e2162f405d9c18
roundtrip: true
bad tag decrypt: auth failed

Java v27.0.1

v27.0.1
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.HexFormat;
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Main {
    public static void main(String[] args) throws Exception {
        // 固定演示 key/iv,输出可跨语言确定性对照
        byte[] key = new byte[32];
        for (int i = 0; i < 32; i++) key[i] = (byte) i;
        byte[] iv = new byte[12];
        for (int i = 0; i < 12; i++) iv[i] = (byte) i;
        byte[] aad = "header-v1".getBytes(StandardCharsets.UTF_8);
        byte[] pt = "top secret payload".getBytes(StandardCharsets.UTF_8);

        Cipher enc = Cipher.getInstance("AES/GCM/NoPadding");
        enc.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"),
                new GCMParameterSpec(128, iv));
        enc.updateAAD(aad);
        byte[] ct = enc.doFinal(pt);
        // Java 返回密文||tag 合一数组;PHP 分成两个变量
        byte[] body = Arrays.copyOfRange(ct, 0, ct.length - 16);
        byte[] tag = Arrays.copyOfRange(ct, ct.length - 16, ct.length);
        System.out.println("gcm ct+tag: " + HexFormat.of().formatHex(body) + HexFormat.of().formatHex(tag));

        Cipher dec = Cipher.getInstance("AES/GCM/NoPadding");
        dec.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"),
                new GCMParameterSpec(128, iv));
        dec.updateAAD(aad);
        byte[] back = dec.doFinal(ct);
        System.out.println("roundtrip: " + Arrays.equals(back, pt));

        // 篡改 tag:doFinal 必须抛 AEADBadTagException
        byte[] bad = ct.clone();
        bad[bad.length - 1] ^= 1;
        try {
            Cipher dec2 = Cipher.getInstance("AES/GCM/NoPadding");
            dec2.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"),
                    new GCMParameterSpec(128, iv));
            dec2.updateAAD(aad);
            dec2.doFinal(bad);
            System.out.println("bad tag decrypt: ok");
        } catch (javax.crypto.AEADBadTagException e) {
            System.out.println("bad tag decrypt: auth failed");
        }
    }
}
输出
gcm ct+tag: 336da63bb680a169e835b7fbd0901402e2b2152918ea3ccfd5fdf6e2162f405d9c18
roundtrip: true
bad tag decrypt: auth failed

JavaScript v26.13.1

v26.13.1
// crypto.createCipheriv 的 aes-256-gcm:openssl_encrypt() 的对照实现
const crypto = require("node:crypto");

const key = Buffer.from(Array.from({ length: 32 }, (_, i) => i));
const iv = Buffer.from(Array.from({ length: 12 }, (_, i) => i));
const aad = Buffer.from("header-v1");
const msg = Buffer.from("top secret payload");

const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
cipher.setAAD(aad);
const ct = Buffer.concat([cipher.update(msg), cipher.final()]);
const tag = cipher.getAuthTag(); // 对应 PHP 的 $tag 按引用参数
console.log("gcm ct+tag:", ct.toString("hex") + tag.toString("hex"));

const decipher = crypto.createDecipheriv("aes-256-gcm", key, iv);
decipher.setAAD(aad);
decipher.setAuthTag(tag);
console.log("roundtrip:", Buffer.concat([decipher.update(ct), decipher.final()]).equals(msg));

// 翻转一个 tag 位:认证必须失败(抛异常)
const badTag = Buffer.from(tag);
badTag[0] ^= 1;
const decipher2 = crypto.createDecipheriv("aes-256-gcm", key, iv);
decipher2.setAAD(aad);
decipher2.setAuthTag(badTag);
try {
    decipher2.update(ct);
    decipher2.final();
    console.log("bad tag decrypt: ok");
} catch {
    console.log("bad tag decrypt: auth failed");
}
输出
gcm ct+tag: 336da63bb680a169e835b7fbd0901402e2b2152918ea3ccfd5fdf6e2162f405d9c18
roundtrip: true
bad tag decrypt: auth failed

PHP v8.6.0

v8.6.0
// openssl_encrypt 的 aes-256-gcm:tag/aad 参数演示(PHP >= 7.1)。
// 固定 key/iv 使输出可跨语言确定性对照。
$key = hex2bin("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"); // $passphrase 参数对 AES 而言就是原始密钥
$iv  = hex2bin("000102030405060708090a0b"); // GCM 的 12 字节 IV
$aad = "header-v1";     // 附加认证数据:不加密,但被 tag 覆盖
$msg = "top secret payload";
$tag = "";              // 按引用回填,与 C 的 EVP API 一致
$ct  = openssl_encrypt($msg, "aes-256-gcm", $key, OPENSSL_RAW_DATA, $iv, $tag, $aad, 16);
echo "gcm ct+tag: ", bin2hex($ct), bin2hex($tag), "\n";
echo "roundtrip: ", var_export(openssl_decrypt($ct, "aes-256-gcm", $key, OPENSSL_RAW_DATA, $iv, $tag, $aad) === $msg, true), "\n";
$tag[0] = chr(ord($tag[0]) ^ 1); // 翻转一个 tag 位
echo "bad tag decrypt: ", openssl_decrypt($ct, "aes-256-gcm", $key, OPENSSL_RAW_DATA, $iv, $tag, $aad) === false ? "auth failed" : "ok", "\n";
输出
gcm ct+tag: 336da63bb680a169e835b7fbd0901402e2b2152918ea3ccfd5fdf6e2162f405d9c18
roundtrip: true
bad tag decrypt: auth failed

Python v3.15.2

v3.15.2
# 纯 Python 手写 AES-256-GCM,教学向实现。
# 生产环境用 cryptography 包(AESGCM);这里展开内部结构。

SBOX = (
    0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
    0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
    0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15,
    0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75,
    0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84,
    0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf,
    0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8,
    0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2,
    0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73,
    0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb,
    0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79,
    0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08,
    0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a,
    0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e,
    0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf,
    0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16
)

RCON = (0x00,0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80,0x1b,0x36)

def xtime(a):
    a <<= 1
    if a & 0x100:
        a ^= 0x11b
    return a & 0xff

def mul(a, b):
    out = 0
    while b:
        if b & 1:
            out ^= a
        a = xtime(a)
        b >>= 1
    return out

def aes256_key_expand(key):
    # 60 个轮密钥字(15 轮,每轮 4 字)
    w = list(key)
    i = 32
    while len(w) < 60 * 4:
        temp = w[i - 4:i]
        if i % 32 == 0:
            temp = [SBOX[b] for b in temp[1:] + temp[:1]]
            temp[0] ^= RCON[i // 32]
        elif i % 32 == 16:
            temp = [SBOX[b] for b in temp]
        w.extend(w[i - 32 + j] ^ t for j, t in enumerate(temp))
        i += 4
    return w

def aes256_encrypt_block(w, blk):
    s = list(blk)

    def add_round_key(rnd):
        for i in range(16):
            s[i] ^= w[rnd * 16 + i]

    def sub_bytes():
        for i in range(16):
            s[i] = SBOX[s[i]]

    def shift_rows():
        # 状态按列主序:索引 = 4 * 列 + 行
        t = s[:]
        for r in range(1, 4):
            row = [t[4 * c + r] for c in range(4)]
            row = row[r:] + row[:r]
            for c in range(4):
                s[4 * c + r] = row[c]

    def mix_columns():
        for c in range(4):
            a = s[4 * c:4 * c + 4]
            s[4 * c] = mul(a[0], 2) ^ mul(a[1], 3) ^ a[2] ^ a[3]
            s[4 * c + 1] = a[0] ^ mul(a[1], 2) ^ mul(a[2], 3) ^ a[3]
            s[4 * c + 2] = a[0] ^ a[1] ^ mul(a[2], 2) ^ mul(a[3], 3)
            s[4 * c + 3] = mul(a[0], 3) ^ a[1] ^ a[2] ^ mul(a[3], 2)

    add_round_key(0)
    for rnd in range(1, 14):
        sub_bytes()
        shift_rows()
        mix_columns()
        add_round_key(rnd)
    sub_bytes()
    shift_rows()
    add_round_key(14)
    return bytes(s)

def gf_mul_gcm(x, y):
    # GHASH 乘法:GF(2^128),位反转表示的 GCM 多项式
    z = 0
    v = x
    for i in range(127, -1, -1):
        if (y >> i) & 1:
            z ^= v
        v = (v >> 1) ^ (0xe1000000000000000000000000000000 if v & 1 else 0)
    return z

def ghash(h, data):
    h_int = int.from_bytes(h, "big")
    x = 0
    for off in range(0, len(data), 16):
        block = data[off:off + 16].ljust(16, b"\x00")
        x = gf_mul_gcm(x ^ int.from_bytes(block, "big"), h_int)
    return x.to_bytes(16, "big")

def aes256_gcm_encrypt(key, iv, pt, aad):
    w = aes256_key_expand(key)
    h = aes256_encrypt_block(w, b"\x00" * 16)
    j0 = iv + b"\x00\x00\x00\x01"
    # CTR 模式:密钥流来自 E(iv || 计数器),计数器从 2 开始
    ct = bytearray()
    counter = 2
    for off in range(0, len(pt), 16):
        ks = aes256_encrypt_block(w, iv + counter.to_bytes(4, "big"))
        for i, b in enumerate(pt[off:off + 16]):
            ct.append(b ^ ks[i])
        counter += 1
    # GHASH 输入:aad || ct || [len(aad)*8]_64 || [len(ct)*8]_64,
    # 各段分别补零到 16 字节整块
    g = aad
    g += b"\x00" * (-len(aad) % 16)
    g += bytes(ct)
    g += b"\x00" * (-len(ct) % 16)
    g += (len(aad) * 8).to_bytes(8, "big") + (len(ct) * 8).to_bytes(8, "big")
    s = ghash(h, g)
    tag = bytes(a ^ b for a, b in zip(s, aes256_encrypt_block(w, j0)))
    return bytes(ct), tag

def aes256_gcm_decrypt(key, iv, ct, aad, tag):
    w = aes256_key_expand(key)
    h = aes256_encrypt_block(w, b"\x00" * 16)
    j0 = iv + b"\x00\x00\x00\x01"
    g = aad + b"\x00" * (-len(aad) % 16)
    g += ct + b"\x00" * (-len(ct) % 16)
    g += (len(aad) * 8).to_bytes(8, "big") + (len(ct) * 8).to_bytes(8, "big")
    s = ghash(h, g)
    expect = bytes(a ^ b for a, b in zip(s, aes256_encrypt_block(w, j0)))
    if expect != tag:
        return None
    pt = bytearray()
    counter = 2
    for off in range(0, len(ct), 16):
        ks = aes256_encrypt_block(w, iv + counter.to_bytes(4, "big"))
        for i, b in enumerate(ct[off:off + 16]):
            pt.append(b ^ ks[i])
        counter += 1
    return bytes(pt)

key = bytes(range(32))
iv = bytes(range(12))
aad = b"header-v1"
pt = b"top secret payload"
ct, tag = aes256_gcm_encrypt(key, iv, pt, aad)
print("gcm ct+tag:", (ct + tag).hex())
print("roundtrip:", "true" if aes256_gcm_decrypt(key, iv, ct, aad, tag) == pt else "false")
bad = bytearray(tag)
bad[0] ^= 1
print("bad tag decrypt:", "ok" if aes256_gcm_decrypt(key, iv, ct, aad, bytes(bad)) is not None else "auth failed")
输出
gcm ct+tag: 336da63bb680a169e835b7fbd0901402e2b2152918ea3ccfd5fdf6e2162f405d9c18
roundtrip: true
bad tag decrypt: auth failed

Rust v1.99.1

v1.99.1
use aes::cipher::{BlockEncrypt, KeyInit};
use aes::Aes256;

fn hex(b: &[u8]) -> String {
    b.iter().map(|x| format!("{:02x}", x)).collect()
}

// GHASH 乘法:GF(2^128),位反转表示,R = 0xe1...
fn gf_mul(x: u128, y: u128) -> u128 {
    let mut z: u128 = 0;
    let mut v = x;
    for i in (0..128).rev() {
        if (y >> i) & 1 == 1 {
            z ^= v;
        }
        v = (v >> 1) ^ if v & 1 == 1 { 0xe1000000000000000000000000000000 } else { 0 };
    }
    z
}

    // 把一个 16 字节块(补零)累加进 GHASH 状态
fn ghash_block(h: u128, x: &mut u128, block: &[u8]) {
    let mut buf = [0u8; 16];
    buf[..block.len()].copy_from_slice(block);
    *x = gf_mul(*x ^ u128::from_be_bytes(buf), h);
}

fn main() {
    let key: [u8; 32] = core::array::from_fn(|i| i as u8);
    let cipher = Aes256::new(&key.into());

    let mut j0 = [0u8; 16];
    j0[..12].copy_from_slice(&[0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]); // iv || 0x00000001
    j0[15] = 1;

    // H = E(K, 0 的 128 位块)
    let h_block = aes::Block::from([0u8; 16]);
    let mut h_out = h_block;
    cipher.encrypt_block(&mut h_out);
    let h = u128::from_be_bytes(h_out.into());

    // CTR 密钥流:E(K, iv || 计数器),计数器从 2 开始
    let pt = b"top secret payload";
    let mut ct = Vec::new();
    let mut counter: u32 = 2;
    for chunk in pt.chunks(16) {
        let mut block = j0;
        block[12..16].copy_from_slice(&counter.to_be_bytes());
        let mut ks = aes::Block::from(block);
        cipher.encrypt_block(&mut ks);
        let ks: [u8; 16] = ks.into();
        for (i, &b) in chunk.iter().enumerate() {
            ct.push(b ^ ks[i]);
        }
        counter += 1;
    }

    // GHASH 输入:aad || ct || [len(aad)*8]_64 || [len(ct)*8]_64
    let aad = b"header-v1";
    let mut x: u128 = 0;
    ghash_block(h, &mut x, aad);
    for chunk in ct.chunks(16) {
        ghash_block(h, &mut x, chunk);
    }
    let mut len_block = [0u8; 16];
    len_block[..8].copy_from_slice(&(aad.len() as u64 * 8).to_be_bytes());
    len_block[8..].copy_from_slice(&(ct.len() as u64 * 8).to_be_bytes());
    ghash_block(h, &mut x, &len_block);

    // tag = GHASH 结果 异或 E(K, J0)
    let mut s = aes::Block::from(j0);
    cipher.encrypt_block(&mut s);
    let s: [u8; 16] = s.into();
    let tag = x ^ u128::from_be_bytes(s);

    let tag_bytes = tag.to_be_bytes();
    println!("gcm ct+tag: {}{}", hex(&ct), hex(&tag_bytes));

    // 解密回读:先重算 GHASH 比对再放出明文
    let mut x2: u128 = 0;
    ghash_block(h, &mut x2, aad);
    for chunk in ct.chunks(16) {
        ghash_block(h, &mut x2, chunk);
    }
    let mut len_block2 = [0u8; 16];
    len_block2[..8].copy_from_slice(&(aad.len() as u64 * 8).to_be_bytes());
    len_block2[8..].copy_from_slice(&(ct.len() as u64 * 8).to_be_bytes());
    ghash_block(h, &mut x2, &len_block2);
    let expect = x2 ^ u128::from_be_bytes(s);
    println!("roundtrip: {}", expect == u128::from_be_bytes(tag_bytes));

    // 翻转一个 tag 位:重算的 GHASH 不再匹配
    let mut bad = tag_bytes;
    bad[0] ^= 1;
    let mut x3: u128 = 0;
    ghash_block(h, &mut x3, aad);
    for chunk in ct.chunks(16) {
        ghash_block(h, &mut x3, chunk);
    }
    ghash_block(h, &mut x3, &len_block2);
    let expect3 = x3 ^ u128::from_be_bytes(s);
    println!("bad tag decrypt: {}", if expect3 == u128::from_be_bytes(bad) { "ok" } else { "auth failed" });
}
输出
gcm ct+tag: 336da63bb680a169e835b7fbd0901402e2b2152918ea3ccfd5fdf6e2162f405d9c18
roundtrip: true
bad tag decrypt: auth failed

TypeScript v26.13.1

v26.13.1
// crypto.createCipheriv 的 aes-256-gcm:openssl_encrypt() 的对照实现
import { createCipheriv, createDecipheriv } from "node:crypto";

const key = Buffer.from(Array.from({ length: 32 }, (_, i) => i));
const iv = Buffer.from(Array.from({ length: 12 }, (_, i) => i));
const aad = Buffer.from("header-v1");
const msg = Buffer.from("top secret payload");

const cipher = createCipheriv("aes-256-gcm", key, iv);
cipher.setAAD(aad);
const ct = Buffer.concat([cipher.update(msg), cipher.final()]);
const tag = cipher.getAuthTag(); // 对应 PHP 的 $tag 按引用参数
console.log("gcm ct+tag:", ct.toString("hex") + tag.toString("hex"));

const decipher = createDecipheriv("aes-256-gcm", key, iv);
decipher.setAAD(aad);
decipher.setAuthTag(tag);
console.log("roundtrip:", Buffer.concat([decipher.update(ct), decipher.final()]).equals(msg));

// 翻转一个 tag 位:认证必须失败(抛异常)
const badTag = Buffer.from(tag);
badTag[0] ^= 1;
const decipher2 = createDecipheriv("aes-256-gcm", key, iv);
decipher2.setAAD(aad);
decipher2.setAuthTag(badTag);
try {
  decipher2.update(ct);
  decipher2.final();
  console.log("bad tag decrypt: ok");
} catch {
  console.log("bad tag decrypt: auth failed");
}
输出
gcm ct+tag: 336da63bb680a169e835b7fbd0901402e2b2152918ea3ccfd5fdf6e2162f405d9c18
roundtrip: true
bad tag decrypt: auth failed

语言差异说明

本批 special:openssl 在 CI 完全可跑——真函数满血演示 + 确定性预置输出。

C/C++:示例手写 AES-256(SBOX 表)+ GHASH(GF(2^128) 乘法);实战用 OpenSSL EVP_aes_256_gcm(EVP_EncryptUpdate/EVP_CIPHER_CTX_ctrl 取 tag)。

C#:AesGcm(.NET 5+)原生,Encrypt/Decrypt 的 tag 参数与 PHP 的按引用 tag 一一对应。

Go:crypto/aes + cipher.NewGCM,Seal 输出密文||tag。

Java:Cipher.getInstance("AES/GCM/NoPadding") + GCMParameterSpec;doFinal 返回密文||tag 合一数组,验签失败抛 AEADBadTagException。

JavaScript:createCipheriv("aes-256-gcm", ...) + getAuthTag();浏览器侧 WebCrypto 的 AES-GCM 仅支持 12 字节 IV 且 tag 拼在密文尾部。

PHP:$passphrase 参数名有误导——对 AES 它就是原始密钥(短了补零、长了截断,没有 KDF);OPENSSL_RAW_DATA 返回原始二进制;tag 由引用回填,传输形态常见「ct || tag || iv」。

Python:cryptography 包的 AESGCM 是生产路线;示例纯 Python 手写(SBOX 用 GF(2^8) 逆元+仿射生成并多源核对)。

Rust:aes crate 提供 AES-256 单块加密,GHASH 用 u128 手写(标准库路线拼装,不引 aes-gcm crate)。

TypeScript:同 JavaScript。PHP 双加密生态:sodium(现代、默认推荐)与 openssl(历史包袱、算法面广)并存——新代码优先 sodium_crypto_secretbox,openssl 留给 TLS/PKI 生态与遗留互操作。