Reputation: 789
I am trying to create a hashing function with user interaction. The idea is that the user chooses which hash he/she wants (i.e. md5, sha1 and so forth) and the program does the rest.
My code:
hashstring = "hashlib" + finalHash
filePath = open(chosenFile, 'rb')
data = filePath.read(8192)
if not data:
return
hashstring.update(data) # The line that causes error
return hashstring.hexdigest()
finalHash
is from a dictionary containing (lets say md5 is chosen) '.md5()'
so the string from hashstring
is 'hashlib.md5()
.
I get the error: AttributeError: 'str' object has no attribute 'update'
, the error points me to the obvious: hashstring
is a string (as i declared it), my question goes: How do i convert or in other way make it useable as it is intended?
Upvotes: 1
Views: 807
Reputation: 288190
You could use getattr
:
import hashlib
chosenFile = '/etc/passwd'
finalHash = input('Which hash function?') # raw_input in Python 2
assert finalHash in ['md5', 'sha1'] # Optional
h = getattr(hashlib, finalHash)
h.update(open(chosenFile, 'rb').read())
print(h.hexdigest())
Note that the input must not contain dots or parentheses. If you want to allow the user to input md5()
or so, you'll have to strip the parentheses first.
Upvotes: 2