AES-GCM 256-Bit Encryption Tool

Encrypt and decrypt text using authenticated AES-GCM 256-bit encryption and PBKDF2 key derivation in your browser.

4.9 / 5· 148 verified ratings
•
100% Client-Side Privacy
•
Verified 2026 Engine
Loading tool engine...
Frequently Used With:Base64 Encoder & Decoder →MD5 Hash Generator →JWT Decoder →HMAC Signature Generator →
Institutional-Grade Accuracy & Client-Side Privacy Guarantee

Unlike conventional calculator sites that send your financial numbers, payload data, or code snippets across remote web servers, Affi-Chain processes all mathematical derivations, algorithms, and data parsing 100% locally within your browser sandbox. No tracking cookies, no server-side retention, and zero transmission lag.

Architecture & Internal Mechanics of AES-GCM

The Advanced Encryption Standard (AES) is the international symmetric block cipher benchmark standardized by the National Institute of Standards and Technology (NIST) in 2001 via FIPS PUB 197. Selected through a multi-year global evaluation of the Rijndael cipher (designed by Belgian cryptographers Vincent Rijmen and Joan Daemen), AES supersedes the legacy Data Encryption Standard (DES) and Triple-DES (3DES).

When deployed in Galois/Counter Mode (AES-GCM) (NIST SP 800-38D), it functions as an Authenticated Encryption with Associated Data (AEAD) cipher. AEAD guarantees both confidentiality (encryption of the payload) and authenticity/integrity (assurance that ciphertext, initialization vector, and metadata have not undergone bit-flipping, truncation, or tampering in transit).

+---------------------------------------------------------------------------------------------------+
|                                  AES-GCM PIPELINED AEAD ARCHITECTURE                              |
+---------------------------------------------------------------------------------------------------+
|  PLAINTEXT BLOCKS (P1, P2... Pn)                 ASSOCIATED DATA (AAD)                            |
|       |               |                                |                                          |
|      (XOR)           (XOR)                             |                                          |
|       ^               ^                                v                                          |
|   AES_K(IV||1)    AES_K(IV||2)              GHASH MULTIPLIER (GF(2^128))                          |
|       |               |                                |                                          |
|       v               v                                v                                          |
|  CIPHERTEXT (C1)  CIPHERTEXT (C2) ---------> [GHASH AUTHENTICATOR]                               |
|                                                        |                                          |
|                                                       (XOR) <--- AES_K(IV||0) (Mask Key)          |
|                                                        |                                          |
|                                                        v                                          |
|                                              128-BIT AUTHENTICATION TAG                           |
+---------------------------------------------------------------------------------------------------+

The Substitution-Permutation Network (SPN)

AES operates on a fixed 128-bit (16-byte) block size arranged in a $4 \times 4$ byte state matrix. Depending on key length (128, 192, or 256 bits), AES executes 10, 12, or 14 transformation rounds respectively. Each standard round executes four atomic mathematical operations:

  1. SubBytes: Non-linear byte substitution where each byte is replaced using an invertible 8-bit S-box constructed via multiplicative inversion in the Galois field $\text{GF}(2^8)$ followed by an affine transformation. This provides high algebraic non-linearity to thwart linear and differential cryptanalysis.
  2. ShiftRows: Cyclical byte permutation where Row 0 is shifted by 0 bytes, Row 1 by 1 byte left, Row 2 by 2 bytes left, and Row 3 by 3 bytes left, ensuring cross-column diffusion.
  3. MixColumns: Linear matrix multiplication where each column of 4 bytes is treated as a polynomial over $\text{GF}(2^8)$ and multiplied modulo $x^4 + 1$ with a fixed polynomial $c(x) = {03}x^3 + {01}x^2 + {01}x + {02}$.
  4. AddRoundKey: Bitwise XOR ($\oplus$) of the intermediate state matrix with a 128-bit round subkey derived from the master cryptographic key via the Rijndael key expansion schedule.

Galois/Counter Mode (GCM) Specification

Unlike legacy modes that require complex padding schemes (such as PKCS#7 in CBC mode), AES-GCM transforms AES into a stream cipher:

1. Counter-Mode Keystream Generation

Given a 96-bit Initialization Vector ($IV$) and a 32-bit counter initialized at $J_0 = IV \mathbin{\Vert} 0^{31}1$:

$$C_i = P_i \oplus \text{AES}K(\text{incr}(J{i-1}))$$

Because plaintext is XORed directly with the AES keystream, no padding is necessary. Payloads of arbitrary byte length can be encrypted without ciphertext expansion.

2. GHASH Polynomial Authentication over $\text{GF}(2^{128})$

Integrity and authentication are computed over both the ciphertext and unencrypted Additional Authenticated Data (AAD) using polynomial evaluation over the binary Galois field $\text{GF}(2^{128})$ defined by the irreducible polynomial:

$$f(x) = x^{128} + x^7 + x^2 + x + 1$$

The hash key $H$ is generated by encrypting a 128-bit block of zeros: $H = \text{AES}_K(0^{128})$.

The GHASH function processes zero-padded AAD blocks followed by zero-padded ciphertext blocks, ending with a 128-bit block encoding their respective bit lengths:

$$S = \text{GHASH}_H(\text{AAD} \mathbin{\Vert} C \mathbin{\Vert} \text{len}(\text{AAD}) \mathbin{\Vert} \text{len}(C))$$

The final 128-bit Authentication Tag $T$ is obtained by masking $S$ with the encrypted initial counter:

$$T = S \oplus \text{AES}_K(J_0)$$


Production Code Implementation

Python: Industrial AES-256-GCM AEAD Engine with PBKDF2 Key Derivation

#!/usr/bin/env python3
"""
Production-Grade AES-256-GCM Authenticated Encryption Engine
with PBKDF2 Key Derivation (HMAC-SHA256, 600,000 iterations).
"""

import os
from typing import Dict, Tuple
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives import hashes


class AES256GCMEngine:
    KEY_LENGTH_BYTES = 32     # 256 bits
    SALT_LENGTH_BYTES = 16    # 128 bits
    NONCE_LENGTH_BYTES = 12   # 96 bits (Standard NIST SP 800-38D IV)
    KDF_ITERATIONS = 600_000  # OWASP 2024+ recommendation

    @classmethod
    def derive_key(cls, passphrase: str, salt: bytes) -> bytes:
        """
        Derives an ephemeral 256-bit symmetric key from a user passphrase using PBKDF2.
        """
        kdf = PBKDF2HMAC(
            algorithm=hashes.SHA256(),
            length=cls.KEY_LENGTH_BYTES,
            salt=salt,
            iterations=cls.KDF_ITERATIONS,
        )
        return kdf.derive(passphrase.encode("utf-8"))

    @classmethod
    def encrypt(
        cls, plaintext: bytes, passphrase: str, associated_data: bytes = b""
    ) -> Dict[str, bytes]:
        """
        Encrypts payload using AES-256-GCM with fresh cryptographically secure Salt and IV.
        The resulting ciphertext encapsulates the 16-byte GHASH tag appended at the end.
        """
        salt = os.urandom(cls.SALT_LENGTH_BYTES)
        nonce = os.urandom(cls.NONCE_LENGTH_BYTES)
        key = cls.derive_key(passphrase, salt)

        aesgcm = AESGCM(key)
        # In python-cryptography, AESGCM.encrypt appends the 16-byte tag to the ciphertext
        ciphertext_with_tag = aesgcm.encrypt(nonce, plaintext, associated_data)

        ciphertext = ciphertext_with_tag[:-16]
        tag = ciphertext_with_tag[-16:]

        return {
            "salt": salt,
            "nonce": nonce,
            "ciphertext": ciphertext,
            "tag": tag,
            "payload_wire": salt + nonce + ciphertext_with_tag,
        }

    @classmethod
    def decrypt(
        cls,
        payload_wire: bytes,
        passphrase: str,
        associated_data: bytes = b"",
    ) -> bytes:
        """
        Parses wire format, reconstructs key, and verifies AEAD integrity prior to returning plaintext.
        Raises InvalidTag if tampering or bit-flipping occurred.
        """
        s_len = cls.SALT_LENGTH_BYTES
        n_len = cls.NONCE_LENGTH_BYTES

        if len(payload_wire) < s_len + n_len + 16:
            raise ValueError("Malformed ciphertext: payload shorter than cryptographic headers.")

        salt = payload_wire[:s_len]
        nonce = payload_wire[s_len : s_len + n_len]
        ciphertext_and_tag = payload_wire[s_len + n_len :]

        key = cls.derive_key(passphrase, salt)
        aesgcm = AESGCM(key)

        # Decrypt will raise cryptography.exceptions.InvalidTag if authentication fails
        plaintext = aesgcm.decrypt(nonce, ciphertext_and_tag, associated_data)
        return plaintext


# Demonstration
if __name__ == "__main__":
    secret_data = b"Financial Ledger Entry: Transfer $25,000,000 to Escrow Account 8923."
    aad_metadata = b"Header: Account-ID=90210; Region=US-East; Nonce-Sequence=44"
    password = "MasterDatabaseClusterEncryptionPassphrase!2026"

    # Encryption
    enc_result = AES256GCMEngine.encrypt(secret_data, password, associated_data=aad_metadata)
    print("--- AES-256-GCM ENCRYPTION SUCCESSFUL ---")
    print(f"Wire Payload Length: {len(enc_result['payload_wire'])} bytes")
    print(f"Salt (Hex):          {enc_result['salt'].hex()}")
    print(f"Nonce/IV (Hex):      {enc_result['nonce'].hex()}")
    print(f"Ciphertext (Hex):    {enc_result['ciphertext'].hex()[:48]}...")
    print(f"Auth Tag (Hex):      {enc_result['tag'].hex()}")

    # Decryption
    decrypted = AES256GCMEngine.decrypt(enc_result["payload_wire"], password, associated_data=aad_metadata)
    assert decrypted == secret_data
    print(f"\nDecrypted Plaintext: {decrypted.decode('utf-8')}")

TypeScript: Web Crypto API AEAD Implementation

/**
 * Modern browser and Node.js Web Crypto API AES-GCM Implementation
 */

export interface EncryptedEnvelope {
  ivHex: string;
  tagHex: string;
  ciphertextHex: string;
}

export async function encryptAESGCM(
  rawKeyBytes: Uint8Array,
  plaintextBytes: Uint8Array,
  additionalDataBytes: Uint8Array = new Uint8Array()
): Promise<EncryptedEnvelope> {
  const cryptoKey = await crypto.subtle.importKey(
    "raw",
    rawKeyBytes,
    { name: "AES-GCM" },
    false,
    ["encrypt"]
  );

  const iv = crypto.getRandomValues(new Uint8Array(12)); // 96-bit standard nonce

  const encryptedBuffer = await crypto.subtle.encrypt(
    {
      name: "AES-GCM",
      iv,
      additionalData: additionalDataBytes,
      tagLength: 128, // 16 bytes
    },
    cryptoKey,
    plaintextBytes
  );

  const totalLength = encryptedBuffer.byteLength;
  const ciphertextBytes = new Uint8Array(encryptedBuffer, 0, totalLength - 16);
  const tagBytes = new Uint8Array(encryptedBuffer, totalLength - 16, 16);

  const toHex = (buf: Uint8Array) => Array.from(buf).map(b => b.toString(16).padStart(2, "0")).join("");

  return {
    ivHex: toHex(iv),
    tagHex: toHex(tagBytes),
    ciphertextHex: toHex(ciphertextBytes),
  };
}

Symmetric Cipher Modes Comparison Matrix

ModeAEAD Authenticated?Cipher TypePadding Required?Parallel ProcessingHardware AccelerationVulnerability to Nonce Reuse
AES-GCMYes (GHASH)Stream-like (CTR)NoBoth Encrypt & DecryptExcellent (AES-NI + CLMUL)Catastrophic (Key recovery)
ChaCha20-Poly1305Yes (Poly1305)Pure StreamNoFully parallelizableExcellent (Vector SIMD / AVX2)Catastrophic (Tag forgery)
AES-CBCNo (Confidentiality only)BlockYes (PKCS#7)Decrypt onlyHigh (AES-NI)Moderate (IV collision leak)
AES-CTRNoStream-likeNoBoth Encrypt & DecryptHigh (AES-NI)Fatal (Keystream XOR reuse)
AES-XTSNo (Tweakable)Sector/BlockNo (Ciphertext stealing)Fully parallelizableHigh (AES-NI)Low (Disk storage mode only)

Catastrophic Pitfalls & Implementation Traps

1. The Catastrophic Nonce-Reuse Disaster (The "Forbidden Attack")

The most severe architectural vulnerability in AES-GCM occurs when the same key and IV combination is used to encrypt two distinct plaintexts:

  • Since $C_1 = P_1 \oplus \text{Keystream}$ and $C_2 = P_2 \oplus \text{Keystream}$, an eavesdropper XORs ciphertexts: $C_1 \oplus C_2 = P_1 \oplus P_2$, stripping encryption completely.
  • Furthermore, by analyzing the two GHASH equations, an attacker can solve for the GHASH hash key $H$ as a root of a polynomial over $\text{GF}(2^{128})$. Once $H$ is derived, the attacker can forge valid authentication tags for arbitrary forged messages, completely dismantling the system's security.

Rule of Thumb: When generating random 96-bit IVs, standard probability limits dictate that after approximately $2^{32}$ encryptions under the same key, collision probability exceeds acceptable bounds (the Birthday Paradox). Keys must be rotated well before $2^{32}$ operations, or deterministic counter nonces must be enforced.

2. Unauthenticated Plaintext Release Before Tag Verification

In streaming or memory-constrained implementations, developers occasionally stream decrypted plaintext chunks to disk or consumer sockets before the final 16-byte authentication tag has been evaluated.

  • If the stream is intercepted by an attacker who modifies payload bytes, the client process will execute business logic on forged unauthenticated data before the abort exception is triggered.
  • Remediation: Decryption engines must buffer decrypted bytes in memory and release plaintext only after constant-time tag verification returns success.

3. Deprecated Padding Oracle Attacks on AES-CBC

Developers transitioning from AES-CBC must recognize that CBC mode is structurally vulnerable to padding oracle attacks (e.g., POODLE, Lucky Thirteen) unless combined with an external HMAC under the strict Encrypt-then-MAC paradigm. AES-GCM natively prevents padding attacks because it possesses zero padding and binds authentication intrinsically.

4. Side-Channel Cache Timing Attacks on Software AES

Software implementations of AES that evaluate the SubBytes S-box using precomputed memory lookup tables (T-tables) leak cryptographic key material through CPU L1 cache access timing variations. Modern cryptographic engines must utilize hardware-accelerated instructions (Intel AES-NI, ARM ARMv8 Cryptography Extensions) or bit-sliced implementations that execute in constant instruction cycles regardless of key or plaintext bits.

Frequently Asked Questions

Why is AES-GCM preferred over AES-CBC?
AES-GCM is an authenticated encryption cipher (AEAD) that provides confidentiality and built-in tamper resistance against padding-oracle attacks.

Explore Related Utilities