Sunday, July 22, 2007

Script to do encryption of files and directories

I have been working on a script that encrypts and decrypts files and directories in Linux. I could have used GnuPG but I wanted to try a different method that does not need to generate a public and private key. In the long run gpg offers a stronger encryption method that using openssl. The script generates a .des3 file that is first compressed and then encrypted.


function getpass() {
stty -echo
echo -n "$2"
read pw
stty echo
eval "$1=$pw"

function usage() {
echo "crypt - encryptor and decrytor utility."
echo -e "\tcrypt e [Directory or File to be encrypted]"
echo -e "\tcrypt d [File to be decripted]"
exit 1

if [ "$1" = "e" ]; then
if [ ! -e "$2" ]; then
echo "Error: An invalid file or directory name to encrypt was given."
getpass pass "Enter the password: "
getpass passconfirm "Re-enter the password: "
if [ "$pass" != "$passconfirm" ]; then
echo "Error: Passwords did not match."

tar -czpf - "$2" | openssl des3 -salt -k "$pass" | dd of="`basename "$2"`.des3" > /dev/null 2>&1
exit 0

if [ "$1" = "d" ]; then
if [ ! -f "$2" ]; then
echo "Error: An invalid file to decrypt was given."
getpass pass "Enter the password to decrypt the file: "
tmpfile="/tmp/`echo \"$2\" | sed 's/\.des3$//'`.tar.gz"
openssl des3 -d -salt -k "$pass" -in "$2" -out "$tmpfile" > /dev/null 2>&1
if [ "$?" -eq 1 ]; then
echo "Error: invalid password was given."
rm -f "$tmpfile"
exit 1
tar xzpf "$tmpfile"
rm -f "$tmpfile"
exit 0

# end of script

1 comment:

Anonymous said...


Finally got around to getting ur script to work on my mac... it should work fine without any changes, but I had some ctrl chars or smthing...

Anyway, encrypt works fine, but decrypt returns this output:
gzip: stdin: decompression OK, trailing garbage ignored
tar: Child returned status 2
tar: Error exit delayed from previous errors

That said, it does decrypt the directory.

Also been meaning to tell you that you can use GnuPG for symmetric encryption (no public/private key-pair) and it gives you access to more algorithms like blowfish, AES, twofish, etc...

well Latrokles out!