0

I am trying to learn python and trying to write a simple script. There seems to be a problem with using a raw_input created variable. I am sure it's simple, but I just don't have the background yet to figure this one out. Here is what I've tried and what works:

#!/usr/bin/python

import hashlib

v = raw_input("Enter your value: ")
print "Which hash algorithm do you want to use?"
# This fails
a = raw_input("md5, sha1, sha224, sha256, sha384, sha512: ")
h = hashlib.a(v)
h.hexdigest()

# This works

v = "password"
h = hashlib.md5(v)
h.hexdigest()
1
  • 1
    replace hashlib.a with getattr(hashlib, a) Commented Aug 26, 2013 at 3:42

2 Answers 2

1

a is just storing a variable with a string value. hashlib.a() is just trying to call a method called a in the hashlib module (which doesnt exist). Try instead using

h = haslib.new(a)
h.update(v)
h.hexdigest()
Sign up to request clarification or add additional context in comments.

Comments

1
hashes = ("md5", "sha1", "sha224", "sha256", "sha384", "sha512")

chosen_hash = None

while not chosen_hash:
    try_hash = raw_input("%s: " % (",".join(hashes))
    if try_hash in hashes:
        chosen_hash = try_hash

hash_func = getattr(hashlib, chosen_hash)()
hash_func.update(v)

As @gos1 suggested, you might use hashlib.new(chosen_hash) instead.

The nice thing is this will guard against someone entering foo as their choice and having your program blow up.

3 Comments

Use a set literal {"md5", "sha1", ...} and this will be perfect.
@sberry I agree. In a real-world application, never let a user enter raw input that might be evaluated, unless you're 100% sure that such evaluation won't break up your program, or worse...
Famous last words "unless you are 100% sure"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.