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
- Create a secure random key: Use OpenSSL to generate a 256-bit AES key. This is essential for security.
openssl rand -base64 32This 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)
- 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 12This command generates a 12-byte (96-bit) random IV in hexadecimal encoding.
Encrypting Data
- 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.pemReplace:
input.txtwith the name of your file to encryptoutput.encwith the desired output filenamepass:'your_password'with a strong password (for key derivation)your_ivwith the IV you generated earlierkey.pemwith the path to your AES key file. You can create this from the base64 output of step 1 usingecho 'base64_key' > key.pem
The
-saltoption adds a random salt for extra security, and-pbkdf2uses Password-Based Key Derivation Function 2 to derive the encryption key from your password.
Decrypting Data
- 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.pemReplace the values as in step 1, ensuring you use the same password and IV used for encryption.
Important Considerations
- Key Security: Protect your AES key! If someone gains access to it, they can decrypt your data.
- IV Uniqueness: Never reuse an IV with the same key. This compromises security.
- Password Strength: Use a strong, unique password if using password-based encryption.
- Authentication Tag: AES-GCM includes an authentication tag to verify data integrity. OpenSSL handles this automatically.

