Use template to construct md5 hash algorithm
algorithm, hash, md5, python
Solution
You could use Jinja2 as a parser, for example:
import hashlib
from jinja2.sandbox import SandboxedEnvironment
def md5(s):
return hashlib.md5(s).hexdigest()
# Sandbox because the source is likely to be untrusted
env = SandboxedEnvironment()
# Parsing any formula, wrapped in {{ ... }}
template = env.from_string('{{md5(salt + md5(password))}}')
# Running it:
hash_ = template.render(md5=md5, salt='3Fd0@5l4x', password='secret')
# hash_ == u'10aaeb818dd269d75bf460469c6b90ab'
As @nathancahill correctly suggests, you could improve this further to include more algorithms:
import functools
def hexify(algorithm):
func = getattr(hashlib, algorithm)
@functools.wraps(func)
def hex_func(s):
return func(s).hexdigest()
return hex_func
algorithms = dict((name, hexify(name)) for name in hashlib.algorithms)
template.render(salt='3Fd0@5l4x', password='secret', **algorithms)
Problem
So this might be a weird one: ``` hashlib.md5((hashlib.md5(salt).hexdigest())+(hashlib.md5(plaintext).hexdigest())).hexdigest() ``` That's MyBB's hashing algorithm. In my python program, that's easy to implement. However, when the hashing algorithm isn't known, and the user is required to enter one, I have no idea how to implement that. So basically I want to hash something with an algorithm that the user enters. If their algorithm is: ``` md5(salt + md5(password)) ``` I want to do: ``` hashlib.md5(salt + hashlib.md5(password).hexdigest()).hexdigest() ``` Help? Oh, and any modules used must be native: pre-included in Python 2.