pythonexceptionunrar

How note a wrong password with Python's UnRAR library?


The following code (which tries to “open” an encrypted RAR-file supplying a wrong password):

from unrar import rarfile
import unrar 

try:
    rarfile.RarFile("encrypted.rar", pwd="wrong_password")
except Exception as e:
    print(type(e))
    print(e)

mostly, though nothing else is wrong with the RAR-file (can be decrypted without errors by using the correct password), outputs:

<class 'unrar.rarfile.BadRarFile'>
Invalid RAR file.

but sometimes it outputs:

<class 'RuntimeError'>
Bad password for Archive

How do I check if a password for a RAR-file is correct with Python's UnRAR library without chaining the exceptions?

In short: UnRAR library raises (randomly?) different exception for the same type of error (namely, wrong password supplied). In most of the cases it raises BadRarFile but sometimes it raises RuntimeError. Catching RuntimeError is bad enough (yet here we can at least check the args), but if one also catches except unrar.rarfile.BadRarFile, one cannot even differentiate between the error that (a) the password is wrong or (b) that the RAR-file is bad.


Solution

  • You could chain multiple except to narrow down the error. Unfortunately, your unrar library seems to raise the unspecific exception RuntimeError in case a bad password is provided. So you cannot be 100% sure if a bad password is the reason for the error.

    try:
        unrar.rarfile.RarFile("encrypted.rar", pwd="wrong_password")
    except unrar.rarfile.BadRarFile:
        print("Specified file doesn't seem to be a proper RAR archive")
    except RuntimeError:
        print("RuntimeError, possibly a wrong password")
    except:
        print("Something else happened")
    

    Other than using different error messages "Wrong password or defective file" and "Wrong password or something else", unfortunately, I don't see any possibility for improvement.

    In short: UnRAR library raises (randomly?) different exception for the same type of error (namely, wrong password supplied). In most of the cases it raises BadRarFile but sometimes it raises RuntimeError.

    It's possible that depending on the version of the RAR file specs, there have been changes how a bad password is being handled. Maybe it isn't possible to differentiate between corrupt files and a wrong password with RAR files of a newer version while this was possible for older files. (Or the other way around.)

    If the "original" unrar command doesn't have this issue, it's possibly a bug upstream in your Python wrapper library.