How to Create a Bash File Encryption Utility

How to Create a Bash File Encryption Utility

How to Create a Bash File Encryption Utility

Encryption is the natural counterpart to the decryption utility covered in the previous article, and building both together makes sense — one produces exactly what the other expects to consume. This article focuses on the encryption side: turning plain files into securely encrypted ones using OpenSSL and GPG, wrapped in a Bash script that handles naming, key derivation, checksums, and safe cleanup.

Before you proceed, please ensure you have OpenSSL installed on your system.

Here’s a basic Bash script that uses OpenSSL to encrypt and decrypt a file:

#!/bin/bash

# Check if a file and password are provided
if [ $# -ne 2 ]; then
    echo "Usage: $0  "
    exit 1
fi

file=$1
password=$2

# Check if the file exists
if [ ! -f "$file" ]; then
    echo "Error: File '$file' not found."
    exit 1
fi

# Encrypt the file using AES-256-CBC
openssl enc -aes-256-cbc -salt -in "$file" -out "$file.enc" -pass pass:"$password"

echo "File '$file' encrypted as '$file.enc'."

Here’s how the script works:

  1. It checks if both a file and a password are provided as command-line arguments. If not, it prints a usage message and exits.
  2. The provided file and password are stored in the file and password variables.
  3. It checks if the file exists. If not, it prints an error message and exits.
  4. It uses OpenSSL to encrypt the file (-aes-256-cbc specifies the AES encryption algorithm in Cipher Block Chaining mode).
  5. The -salt option adds a random salt to the encryption process.
  6. The encrypted file is saved with a .enc extension.
  7. It prints a message indicating that the file has been encrypted.

Usage example:

./encryption_utility.sh file.txt MySecretPassword

This will encrypt file.txt using AES-256-CBC with the password “MySecretPassword” and save the encrypted file as file.txt.enc.

Please note that this is a basic example. Depending on your requirements, you might want to add more features, error handling, or support for different encryption algorithms or methods. Always handle passwords and encryption keys securely.

Exit mobile version