Automator service for encrypting or decrypting with openssl

automatorencryptionservices

Can I create two Automator services that allow me to encrypt or decrypt files? So I would right click a file and click 'Encrypt', the .txt file would be encrypted to a .enc using openssl:

pass=$(osascript -e 'tell app (path to frontmost application as text)
text returned of (display dialog "Enter password:" default answer "")
end')
for f in "$@"; do
    printf %s "$pass" | openssl enc -aes-256-cbc -salt -in "$f" -out "${f%.*}.enc" -pass stdin
done

Can I create a decrypt version that will give me the original .txt file back? Or can I write one service that knows if I want to encrypt or decrypt and run in the way necessary?

Best Answer

Select the service template, change the input type to files, add a Run Shell Script action, select pass input as arguments, and paste this script:

pass() {
    osascript - "$1" <<END
    on run args
    tell app (path to frontmost application as text)
    text returned of (display dialog ("Enter password for " & item 1 of args) default answer "")
    end
    end
END
    [ $? != 0 ] && exit 0
}

for f in "$@"; do
    if [[ "$f" == *.enc ]]; then
        pass "$f" | openssl enc -d -aes-256-cbc -pass stdin -in "$f" -out "${f%.enc}"
    else
        pass "$f.enc" | openssl enc -aes-256-cbc -salt -pass stdin -in "$f" -out "$f.enc"
    fi
done
exit 0

It doesn't show specific error messages, you have to run the service again if you enter a wrong password, and there is no way to use the same password for multiple files. It would be easier to just do it from a shell.