added pbkdf2 support, simplified logic

This commit is contained in:
mdipierro
2012-07-18 12:24:28 -05:00
parent 9cfb1e8afd
commit 1e657f0121
5 changed files with 185 additions and 42 deletions
+9 -7
View File
@@ -16,6 +16,7 @@ import random
import time
import os
import logging
from gluon.contrib.pbkdf2 import pbkdf2_hex
logger = logging.getLogger("web2py")
@@ -32,7 +33,7 @@ def md5_hash(text):
""" Generate a md5 hash with the given text """
return hashlib.md5(text).hexdigest()
def simple_hash(text, digest_alg = 'md5'):
def simple_hash(text, salt = '', digest_alg = 'md5'):
"""
Generates hash with the given text using the specified
digest hashing algorithm
@@ -41,6 +42,8 @@ def simple_hash(text, digest_alg = 'md5'):
raise RuntimeError, "simple_hash with digest_alg=None"
elif not isinstance(digest_alg,str):
h = digest_alg(text)
elif salt:
return hmac_hash(text, salt, digest_alg)
else:
h = hashlib.new(digest_alg)
h.update(text)
@@ -68,13 +71,12 @@ def get_digest(value):
else:
raise ValueError("Invalid digest algorithm")
def hmac_hash(value, key, digest_alg='md5', salt=None):
if ':' in key:
digest_alg, key = key.split(':')
def hmac_hash(value, salt, digest_alg='md5'):
if isinstance(digest_alg,str) and digest_alg.startswith('pbkdf2'):
iterations, keylen = digest_alg[7:-1].split(',')
return pbkdf2_hex(value, salt, int(iterations), int(keylen))
digest_alg = get_digest(digest_alg)
d = hmac.new(key,value,digest_alg)
if salt:
d.update(str(salt))
d = hmac.new(salt,value,digest_alg)
return d.hexdigest()