Skip to content

AES-GCM Encryption

Overview

AES-GCM (AES with Galois/Counter Mode) is an encryption standard that combines high-performance encryption with built-in message integrity.

The inputs for AES-GCM encryption are:

  • arbitrary data: data to be encrypted
  • a key: typically derived from a secure key derivation function like PBKDF2
  • an initialization vector (IV): a unique one-time value used once for each encryption operation

Encryption

Encryption of data is a two-step process. First, we will need to generate a key from a password using a secure key derivation function like PBKDF2. Once we have a key, we can then use it to encrypt our data.

Let's walk through an example of encrypting some arbitrary secret data.

Step 1: Derive a Key

First, we will need to derive a key from a password. We can use the AesGcm.getKey function to do this.

import { AesGcm } from 'ox'
 
const key = await AesGcm.getKey({ password: 'qwerty' })

Step 2: Encrypt Data

Now that we have a key, we can use it to encrypt some data using AesGcm.encrypt.

import { AesGcm, Hex } from 'ox'
 
const key = await AesGcm.getKey({ password: 'qwerty' })
 
const data = Hex.fromString('i am top secret')
 
const encrypted = await AesGcm.encrypt(data, key)

Step 3: Decrypt Data

We can decrypt encrypted data using the AesGcm.decrypt function.

import { AesGcm, Hex } from 'ox'
 
const key = await AesGcm.getKey({ password: 'qwerty' })
 
const data = Hex.fromString('i am top secret')
 
const encrypted = await AesGcm.encrypt(data, key)
 
const decrypted = await AesGcm.decrypt(encrypted, key)

Related Modules

ModuleDescription
AesGcmUtility functions for AES-GCM encryption.