#!/bin/bash
# enc.sh: A simple bash script for deniable encrypting/decrypting file
# headers with AES256. An example application is encrypting encrypted 
# partitions or mass storage devices which do not have a deniable encryption,
# e. g. LUKS. Encrypting the file header (beginning) makes the encryption
# deniable and makes decryption without both passwords practially impossible.
#
# An alternate and openssl-free version can be made with taking hashes like
# sha512sum, sha384sum etc. from the password and xoring them with the
# header ($(($INBYTE1 ^ $INBYTE2))). With xoring the encryption is the
# same than the decryption.
#
# Parameter: <input device> <optional d for decrytption>
#
# Dr. Rolf Freitag 2011. License: Beerware License.
#
# Version 1.0, 2011-06-24: No explicit input parameter checks, no online
# help. Hard coded encryption/decryption of the first 4 kiB (or less if the
# whole file is smaller, but openssls needs at minimum 1024 bytes).
# This version is a little dangerous because for decryption EVERY Password is accepted
# and if it is wrong, the header is not decrypted but encrypted two times!
# Future better versions should avoid this by checking the mime type or magic number.

# Example usage:
# Encryption: enc.sh tmp.txt
# Decryption: enc.sh tmp.txt -d


# set -u -e: Stop the script when a variable isn't set (add -x for debugging)
# and exit the script if any statement returns a non-true return value.
set -u -e 

# get the source = drain
SOURCE="$1"

# Make tmp working directory in /tmp.
# For better security (more secure file storage/deletion) you can use tmps, 
# which is in the RAM (http://en.wikipedia.org/wiki/TMPFS).
TMPDIR0=`mktemp -d -p /tmp ."$RANDOM"_XXX`

# tmp files
TMPFILE0=`mktemp --tmpdir="$TMPDIR0" ."$RANDOM"_XXX`
TMPFILE1=`mktemp --tmpdir="$TMPDIR0" ."$RANDOM"_XXX`

# get the file header = souce
dd if="$SOURCE" of="$TMPFILE0" bs=512 count=8

if [ $# -eq 1 ]
then
  # encrypt
  openssl aes256 -nosalt -nopad -in "$TMPFILE0" -out "$TMPFILE1"
else
  # decrypt
  openssl enc -d -aes256 -nosalt -nopad -in "$TMPFILE0" -out "$TMPFILE1"
fi

# write the encrypted/decrypted header to the drain
dd conv=nocreat,notrunc,noerror oflag=noatime,nofollow of="$SOURCE" if="$TMPFILE1" bs=512 count=8

# make clean
wipe -f -r "$TMPDIR0"

