A script for compressing and encrypting directories

Nov 13, '03 11:01:00AM

Contributed by: Anonymous

I've been frustrated with the encryption options in OS X, especially when the application I'd been using ("Crypt," I believe) started acting buggy after the upgrade to Jaguar. One feature I really wanted was to encrypt/decrypt an entire directory on the fly, without too much mucking on the command line. In the past, I had used GPG for encryption, but it wasn't installed by default on Jaguar. Openssl does have some nice utilities, though.

This script allows for encryption or decryption (I combined two separate scripts) of any directory within the present working directory. All files in the directory are tarred, gzipped, and encrypted using the Blowfish algorithm.

There have been other hints of a similar nature, but this one is better because 1) it uses the built-in openssl, not gpg, and 2) it is extremely flexible, allowing for easy encryption of any directory by just cd-ing to the parent directory. Using rm -P ensures the old files are securely overwritten a few times.

[robg adds: I have not tested this script.]

There may be a much more elegant way to do this, but this is my first shell script. Oh, and since I use bash, much of the syntax may be off for those still using tcsh. It doesn't look like indentation is preserved, so if you can't sort it out, email me and I'll send the raw file. Here 'tis:


#!/bin/bash
# This script compresses and encrypts/decrypts
# entire directories using Blowfish.
dir_name=
mode=
echo "Type \"e\" for encryption, or \"d\" for decryption."
read mode
if [ "$mode" != "e" ]; then
  if [ "$mode" != "d" ]; then
    echo "Invalid entry; please try again"
    exit 1
  else
    #decrypt
    echo -n "Type the name of the directory you wish to decrypt> "
    read dir_name
    if [ -f "${dir_name}.tar.gz.bf" ]; then
      echo ${PWD}'/'${dir_name}.tar.gz.bf "will be decrypted."
      openssl bf -d -in ${dir_name}.tar.gz.bf -out secret_files.tar.gz
      rm -P ${dir_name}.tar.gz.bf
      tar xzvf secret_files.tar.gz
      rm -P secret_files.tar.gz
      echo "Directory \"${dir_name}\" successfully decrypted."
    else
      echo "Unable to find that encrypted directory."
      echo "Please try again.  Exiting program."
      exit 1
   fi
   exit 1
 fi
fi
#encrypt
echo -n "Type the name of the directory you wish to encrypt> "
read dir_name
if [ -d "$dir_name" ]; then
  tar czvf secret_files.tar.gz $dir_name
  rm -rf $dir_name
  openssl bf -in secret_files.tar.gz -out ${dir_name}.tar.gz.bf
  rm -P secret_files.tar.gz
  echo "Directory ${dir_name} successfully encrypted."
else
  echo "That directory doesn't seem to exist."
  echo "Please try again.  Exiting program."
  exit 1
fi
Save the script somewhere on your path and make it executable, of course...

Comments (7)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20031105182205541