lockaes_gcm_encrypt

On-chain AES-256-GCM encryption

Encrypt data on-chain using Mercury EVM's AES-GCM encryption precompile.

Overview

aes_gcm_encrypt() and async_aes_gcm_encrypt() call the AES-GCM encryption precompile at address 0x66 to encrypt plaintext using AES-256-GCM. The ciphertext includes a 16-byte authentication tag.

Signature

def aes_gcm_encrypt(
    w3: Web3,
    *,
    aes_key: Bytes32,
    nonce: int | EncryptionNonce,
    plaintext: bytes,
) -> HexBytes

async def async_aes_gcm_encrypt(
    w3: AsyncWeb3,
    *,
    aes_key: Bytes32,
    nonce: int | EncryptionNonce,
    plaintext: bytes,
) -> HexBytes

Parameters

Parameter
Type
Required
Description

w3

Web3 or AsyncWeb3

Yes

Web3 instance connected to a Seismic node

aes_key

Yes

32-byte AES-256 encryption key

nonce

Yes

12-byte nonce (can be integer or EncryptionNonce)

plaintext

bytes

Yes

Data to encrypt

Returns

Type
Description

HexBytes

Ciphertext bytes (includes 16-byte authentication tag appended)

Examples

Basic Usage

With Integer Nonce

With EncryptionNonce

Async Usage

Encrypt-Decrypt Round Trip

Encrypt Multiple Messages

With ECDH-Derived Key

How It Works

  1. Encode parameters - Concatenates 32-byte key + 12-byte nonce + plaintext

  2. Call precompile - Issues an eth_call to address 0x66 with estimated gas

  3. Encrypt data - Precompile performs AES-256-GCM encryption

  4. Return ciphertext - Returns encrypted data with 16-byte authentication tag appended

Gas Cost

Gas cost is calculated as:

For example:

  • 16 bytes plaintext: 1030 gas

  • 64 bytes plaintext: 1120 gas

  • 256 bytes plaintext: 1480 gas

Notes

  • Uses AES-256-GCM authenticated encryption

  • Nonce must be unique for each encryption with the same key

  • Ciphertext length = plaintext length + 16 bytes (authentication tag)

  • The authentication tag ensures ciphertext integrity

  • Reusing a nonce with the same key breaks security

Warnings

  • Nonce reuse - NEVER reuse the same nonce with the same key (breaks confidentiality)

  • Key security - Keep AES keys secure and never expose them

  • Authentication tag - The 16-byte tag is appended to ciphertext and must be included during decryption

  • Counter management - When using integer nonces, ensure they're sequential and never repeat

See Also

Last updated