#!/bin/bash
# crypt_openssl v0.1
# Copyright (c) 2013 Daniel Lange, http://daniel-lange.com.
# Released into the public domain. NO LIABILITY ACCEPTED WHATSOEVER. USE AT YOUR OWN RISK.

# openssl builds a hash over the CRYPT_KEY keyfile (sha256 chosen below)
# 
CRYPT_KEY="${HOME}/.gnupg/mykey001"
METHOD="enc -e"

if (($# == 0)) || [[ "$1" == "--help" ]] || [[ "$1" == "-h" ]]; then
	echo "Usage: $0 [-d] <filename> [<filename> ...]"
	exit 1
fi

if [[ ! -e "$CRYPT_KEY" ]]; then
	echo "Error: Cryptographic key does not exist on this system."
	exit 2
fi

if [[ "$1" == "--decrypt" ]] || [[ "$1" == "-d" ]]; then
        METHOD="enc -d"
        shift
fi

for INFILE in "$@"; do
	if [[ "$METHOD" =~ " -e" ]] ; then
		OUTFILE=$INFILE.aes
		echo "Encrypting $INFILE to $OUTFILE..."
	else
		OUTFILE=${INFILE%.aes}
		echo "Decrypting $INFILE to $OUTFILE..."
	fi
	
	cat "$CRYPT_KEY" | tr -d "\n\r\000" | openssl $METHOD -aes-256-cbc -pass fd:0 -md sha256 -v -in "$INFILE" -out "$OUTFILE"

done
