Decrypt all PDFs in a directory using the given password and optionally store the password in the Mac OS system keychain
#! /bin/sh | |
# Check if qpdf is installed | |
installed=$(which qpdf &> /dev/null) | |
if [ $? -eq 1 ]; then | |
echo >&2 "Please install qpdf first (brew install qpdf)" | |
exit 1 | |
fi | |
# Fetch the password from the keychain | |
password_entered=false | |
password=$(security 2> /dev/null find-generic-password -a login -s decrypt_pdfs -D "application password" -w) | |
# Prompt for password if not in keychain | |
if [ -z $password ]; then | |
echo "Enter the password to decrypt PDFs:" | |
read -s password | |
password_entered=true | |
fi | |
# Make a folder called 'decrypted' unless it exists | |
mkdir -p decrypted | |
# Decrypt all .pdf files in the current directory | |
for file in *.pdf; do | |
set -e | |
echo "Decrypting $file" | |
qpdf --decrypt --password="$password" "$file" "decrypted/$file" | |
done | |
# Save the password to the keychain | |
if [ $password_entered != false ]; then | |
echo "Save password in keychain?" | |
read yn | |
case $yn in | |
[Yy]* ) security add-generic-password -a login -l pdf_password -s decrypt_pdfs -T "" -w $password; break;; | |
[Nn]* ) exit;; | |
* ) echo "Please answer yes or no.";; | |
esac | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment