ABSP, Ch 13, Practice Project #3

My solution to the Practice Project #3 in Chapter 13 of the excellent book “Automate the Boring Stuff with Python” (ABSP)

import os, sys, PyPDF2, time

print("Enter location of the dictionary (ex: .../dictionary.txt):")
dictLoc = input()
if not os.path.isfile(dictLoc):
    print("Invalid location for dictionary!")
    sys.exit()

print("Enter location of PDF file to decrypt:")
pdfLoc = input()
if not os.path.isfile(pdfLoc):
    print("Invalid location for PDF file!")
    sys.exit()

pdfFile = open(pdfLoc, "rb")
pdfReader = PyPDF2.PdfFileReader(pdfFile)
if pdfReader.isEncrypted != True:
    print("PDF file: " + os.path.basename(pdfLoc) + " is not encrypted!")
    sys.exit()
keysFile = open(dictLoc)
allKeysNewline = keysFile.readlines() # each entry contains a newline "\n" at the end
keysFile.close()
allKeys = []
for i in range(len(allKeysNewline)):
    allKeys.append(allKeysNewline[i].rstrip("\n"))
startTime = time.time()
for key in allKeys:
    if pdfReader.decrypt(key.upper()) == 1:
        print(key.upper() + " is the password")
        endTime = time.time()
        print("It took %s seconds to find the password." % round(endTime-startTime,2))
        sys.exit()
    elif pdfReader.decrypt(key.lower()) == 1:
        print(key.lower() + " is the password")
        endTime = time.time()
        print("It took %s seconds to find the password." % round(endTime-startTime,2))
        sys.exit()
    else:
        continue

print("Sorry, the password of the PDF is not in the dictionary.")

Comments about the code are welcome.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s