Bash – Encrypting/Decrypting a file using openssl through an autorun script

bashopensslshell

So I am trying to encrypt/decrypt a file using openssl. I am running it through a script that is automatically run when I mount a USB, and decrypts
the file. However, it doesn't work quite right, so here are my steps.

I encrypt the text file using…

openssl aes-256-cbc -salt -in file.txt -out file.txt.en -pass pass:123

I then have a script on the usb, which is automatically run when mounted.

autorun.sh

#!/bin/sh
openssl aes-256-cbc -in file.txt.en -out file.txt -d -pass pass:123

Now it doesn't work when the USB tries to run it, however if I run it from console using…

./autorun.sh

It magically works and I am curious as to what the difference is. I also tried running it in interactive mode and that didn't fix my problem.

Best Answer

The difference might be the directory it's executed from. Maybe (probably) the system executes it not from inside the mount point with ./autorun.sh, but from somewhere else using an absolute path like /media/mykey/autorun.sh.

To make the script work when executed from a different directory, using absolute path, write this way:

#!/bin/sh
cd "$(dirname "$0")"
openssl aes-256-cbc -in file.txt.en -out file.txt -d -pass pass:123

Instead of testing this by unplugging and re-plugging, test like this:

cd /tmp
/path/to/mount/point/autorun.sh

If this works, then there's a good chance it will work after you unplug and re-plug.

Related Topic