I would like to allow people to provide the name of a hash function as a means of digitally fingerprinting some object:
def create_ref(obj, hashfn='sha256'):
"""
Returns a tuple of hexdigest and the method used to generate
the digest.
>>> create_ref({}, 'sha1')
('bf21a9e8fbc5a3846fb05b4fa0859e0917b2202f', 'sha1')
>>> create_ref({}, 'md5')
('99914b932bd37a50b983c5e7c90ae93b', 'md5')
"""
return (eval('hashlib.%s' % hashfn)(unicode(obj)).hexdigest(), hashfn)
Is hard coding hashlib sufficently robust to prevent abuse of eval?
instead of eval, try this code:
This will guarantee that the algorithm provided is a valid algorithm. (Note that hashlib.algorithms is new in 2.7, so if you use an older version, replace hashlib.algorithms with a tuple of allowed algorithms.