Search code examples
pythonhashhashlib

How to use a variable as an attribute in python


I wanted to write a Python script to bruteforce hashes that permits the user to insert the hashing algorithm as a string (Result: algorithm = "md5"), but when I tried to use it like this in the hashlib library: guess_hash = hashlib.algorithm(bytes(guess)).hexdigest(), it obviously gave me this error: AttributeError: module 'hashlib' has no attribute 'algorithm' So I did a quick research and I tried using getattr like this: getattr(hashlib,guess(bytes(guess1))).hexdigest() (probably really wrong) and it gave me this error: TypeError: string argument without an encoding. What should I do? Thanks in advance and sorry for the noobiness :)


Solution

  • That's actually bytes complaining (which it will with Python 3 but not Python 2). It would appear that you've also swapped the meanings of algorithm and guess in your getattr, and you'll want to do something like

    getattr(hashlib, algorithm)(bytes(guess, 'utf-8')).hexdigest()