2011-06-17 Encrypting and decrypting files part 2

Some time ago, I gave a duo of one-liners that encrypts/decrypts files.

This wasn't good enough for normal usage, so here's a better version that takes care of directories as well by running tar on them.

  #!/bin/sh
  source="$1"
  if [ -d "$source" ]; then
      newfilename="$source".tar.encrypted
  else
      newfilename="$source".encrypted
  fi
  if [ -e "$newfilename" ]; then
      echo "ERROR: A filename with the name $newfilename already exists"
      exit 1
  fi
  if [ -d "$source" ]; then
      # Source is a directory, first tar it
      if [ -e "$source".tar ]; then
          echo "ERROR: A filename with the name $source.tar already exists"
          exit 1
      fi
      tar cf "$source".tar "$source"
      openssl des3 -salt -in "$source".tar -out "$newfilename"
      rm -f "$source".tar
  else
      openssl des3 -salt -in "$source" -out "$newfilename"
  fi

And its evil twin, decrypt:

 #!/bin/sh
  origfilename=$(basename "$1" .encrypted)
  if [ "$origfilename" == "$1" ]; then
      echo "ERROR: Encrypted files must have the .encrypted extension"
      exit 1
  fi
  if [ -e "$origfilename" ]; then
      echo "ERROR: A filename with the name $origfilename already exists"
      exit 1
  fi
  openssl des3 -d -salt -in "$1" -out "$origfilename"
  # Check if the output is tarred
  tarfilename="$origfilename"
  origfilename=$(basename "$origfilename" .tar)
  if [ "$origfilename" != "$tarfilename" ]; then
      # It was tarred
      if [ -e "$origfilename" ]; then
          echo "ERROR: A filename with the name $origfilename already exists"
          exit 1
      fi
      tar xf "$tarfilename"
      rm "$tarfilename"
  fi

Save them in your path somewhere and make them executable.