Skip to content

Instantly share code, notes, and snippets.

@mickmon
Last active January 4, 2025 16:56
Show Gist options
  • Save mickmon/061a29af55840944c72c7a304f1eb8a7 to your computer and use it in GitHub Desktop.
Save mickmon/061a29af55840944c72c7a304f1eb8a7 to your computer and use it in GitHub Desktop.
A script attempting to use a list of passwords against a gpg key
#!/bin/bash
# File containing passwords to test
PASSWORD_FILE="password_combinations.txt"
# Encrypted file you are trying to decrypt
ENCRYPTED_FILE="/Users/mickmon/Desktop/bwall.key.gpg"
if [ ! -f "$PASSWORD_FILE" ]; then
echo "Password file not found: $PASSWORD_FILE"
exit 1
fi
if [ ! -f "$ENCRYPTED_FILE" ]; then
echo "Encrypted file not found: $ENCRYPTED_FILE"
exit 1
fi
while IFS= read -r passphrase; do
echo "Trying password: $passphrase"
# Attempt decryption
echo "$passphrase" | gpg --batch --yes --decrypt --passphrase-fd 0 --pinentry-mode loopback "$ENCRYPTED_FILE" > decrypted_output.txt 2>&1
# Check if decryption was successful
if [ $? -eq 0 ]; then
echo "Success! Correct password is: $passphrase"
exit 0
fi
done < "$PASSWORD_FILE"
echo "No valid password found."
exit 1
@AndreHeinecke
Copy link

AndreHeinecke commented Jan 4, 2025

decrypt is not suited for such a test since decrypt tries to convert data to plain text and this can work for unencrypted data (e.g. the output of --store) or simply signed data, or signed and encrypted data. Then you have the signature states, e.g. it is a valid signature or an invalid signature. Each of these actions would require different return codes. So simply checking for success or failure invites bad scripts which might make assumptions like. “If this is symetcrically encrypted and I can decrypt it with my password then I know that the sender also knows that password and I can trust that input”. This is why the return code of decrypt should not be used. The correct way to check the decrypt result would involve parsing status-fd.

But checking for the passphrase can be done with --dry-run and --passwd so you can adjust line 22 to:
echo "$passphrase" | gpg --passphrase-fd=0 --pinentry-mode=loopback --dry-run --batch --passwd $KEYID

And have no need for input or output

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment