Skip to content

Instantly share code, notes, and snippets.

@therealshiggins
Created June 29, 2022 13:35
Show Gist options
  • Save therealshiggins/6857cc80d4b68118285eee71327c5e45 to your computer and use it in GitHub Desktop.
Save therealshiggins/6857cc80d4b68118285eee71327c5e45 to your computer and use it in GitHub Desktop.
Paperless-ngx pre-consume script for removing PDF password
#!/bin/bash
########################################
#
# Location of your secret passwords
# One password per line
#
PASSWORDS_FILE=/scripts/.passwords.txt
#
########################################
SCRIPTNAME=$(basename $0)
SOURCE_FILE=${1}
TEMP_FILE="${SOURCE_FILE}.tmp-decrypt"
#
# Check CLI params or print help
#
if [[ -z "$SOURCE_FILE" ]]; then
cat <<EOF
NAME
$SCRIPTNAME - PDF decrypter
SYNOPSIS
$SCRIPTNAME [FILE]
DESCRIPTION
Attepmts to decrypt a password-protected PDF file using a dictionary
of passwords. If successful replaces the original file.
Save your passwords the following file (one password per-line):
$PASSWORDS_FILE
(to change this path, edit the source file: $0)
DISCLAIMER
Use at your own risk.
Works for me; may not work for you.
Absolutely no warranty included.
SEE ALSO
qpdf
EOF
exit
fi
#
# Check file exists
#
if [[ ! -f $SOURCE_FILE ]]; then
echo "File not found: $SOURCE_FILE"
exit
fi
#
# Check file is a PDF
#
if [[ "$SOURCE_FILE" != *.pdf ]]; then
echo "File is not a PDF: $SOURCE_FILE"
exit
fi
#
# Attempt decrypting without password
# Will succeed only when PDF is not encrypted
# We can leave original file untouched
#
if qpdf --decrypt "$SOURCE_FILE" "$TEMP_FILE" >/dev/null 2>&1; then
echo "File does not require decrypting: $SOURCE_FILE"
rm "$TEMP_FILE"
exit
fi
#
# Try to decrypt the PDF using our dictionary of passwords
# TODO: Escape specisl chars
#
while read PASSWORD; do
if qpdf --decrypt --password="$PASSWORD" "$SOURCE_FILE" "$TEMP_FILE" >/dev/null 2>&1; then
echo "File decrypted: $SOURCE_FILE"
touch "$TEMP_FILE" --reference="$SOURCE_FILE"
mv --verbose "$TEMP_FILE" "$SOURCE_FILE"
exit
fi
done < $PASSWORDS_FILE
#
# Stil here? Then we failed at decrypting
#
echo "File could not be decrypted: $SOURCE_FILE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment