Blog | G5 Cyber Security

OpenSSL AES-GCM: Quick Start Guide

TL;DR

This guide shows you how to encrypt and decrypt data using OpenSSL with the AES-GCM cipher. It covers generating a key, creating an IV (initialization vector), encryption, and decryption.

Generating an AES Key

  1. Create a secure random key: Use OpenSSL to generate a 256-bit AES key. This is essential for security.
    openssl rand -base64 32

    This command outputs a 32-byte (256-bit) random key in base64 encoding. Save this key securely – you’ll need it for decryption!

Creating an Initialization Vector (IV)

  1. Generate a unique IV: The IV must be different for each encryption operation, even with the same key. A 12-byte IV is typical for AES-GCM.
    openssl rand -hex 12

    This command generates a 12-byte (96-bit) random IV in hexadecimal encoding.

Encrypting Data

  1. Encrypt the data: Use OpenSSL to encrypt your data using AES-GCM.
    openssl enc -aes-256-gcm -salt -pbkdf2 -in input.txt -out output.enc -pass pass:'your_password' -iv 'your_iv' -keyfile key.pem

    Replace:

    • input.txt with the name of your file to encrypt
    • output.enc with the desired output filename
    • pass:'your_password' with a strong password (for key derivation)
    • your_iv with the IV you generated earlier
    • key.pem with the path to your AES key file. You can create this from the base64 output of step 1 using
      echo 'base64_key' > key.pem

    The -salt option adds a random salt for extra security, and -pbkdf2 uses Password-Based Key Derivation Function 2 to derive the encryption key from your password.

Decrypting Data

  1. Decrypt the data: Use OpenSSL to decrypt the encrypted file.
    openssl enc -aes-256-gcm -d -salt -pbkdf2 -in output.enc -out decrypted.txt -pass pass:'your_password' -iv 'your_iv' -keyfile key.pem

    Replace the values as in step 1, ensuring you use the same password and IV used for encryption.

Important Considerations

Exit mobile version