Shell Snippet: Encrypt Files with AES256

| 1 minute | Comments

#!/usr/bin/env bash
#
# Quickly encrypt a message or a file for sending to
# your colleagues over unsecure messengers (Slack, etc)...
#
#     echo "secret message" | encrypt
#
# Or to encrypt a file:
#
#     encrypt ./path/to/file
#
# -----------------------------------------------------------------------------

FILEPATH="$1"

if [ -z "$FILEPATH" ]; then
    BASE64=$(openssl enc -A -aes256 -base64 -md md5)

    echo
    echo \# Decrypt this message by running:
    echo \# ================================
    echo 
    echo echo \""$BASE64"\" \| openssl enc -d -aes256 -base64 -md md5 -A
    echo 
    echo \# ================================    
    echo
elif [ -f "$FILEPATH" ]; then
    RPATH=$(realpath --relative-base="$HOME" "$FILEPATH")
    BASE64=$(openssl enc -A -aes256 -base64 -md md5 < "$FILEPATH")

    echo
    echo \# Decrypt this file by running:
    echo \# ================================
    echo 
    echo echo \""$BASE64"\" \| openssl enc -d -aes256 -base64 -md md5 -A \> \""~/$RPATH"\"
    echo 
    echo \# ================================
    echo
else
    echo >&2
    echo "ERROR - file not found: $FILEPATH" >&2
    echo >&2
    exit 1
fi
| Written by
Tags: CLI | Shell | Snippet