security.py (1782B)
1 #Embedded file name: C:\BuildAgent\work\20d73f1b24eed06e\eve\release\V24.01\carbon\common\lib\werkzeug\security.py 2 import hmac 3 import string 4 from random import SystemRandom 5 try: 6 from hashlib import sha1, md5 7 _hash_funcs = _hash_mods = {'sha1': sha1, 8 'md5': md5} 9 _sha1_mod = sha1 10 _md5_mod = md5 11 except ImportError: 12 import sha as _sha1_mod, md5 as _md5_mod 13 _hash_mods = {'sha1': _sha1_mod, 14 'md5': _md5_mod} 15 _hash_funcs = {'sha1': _sha1_mod.new, 16 'md5': _md5_mod.new} 17 18 SALT_CHARS = string.letters + string.digits 19 _sys_rng = SystemRandom() 20 21 def gen_salt(length): 22 if length <= 0: 23 raise ValueError('requested salt of length <= 0') 24 return ''.join((_sys_rng.choice(SALT_CHARS) for _ in xrange(length))) 25 26 27 def _hash_internal(method, salt, password): 28 if method == 'plain': 29 return password 30 if salt: 31 if method not in _hash_mods: 32 return 33 if isinstance(salt, unicode): 34 salt = salt.encode('utf-8') 35 h = hmac.new(salt, None, _hash_mods[method]) 36 else: 37 if method not in _hash_funcs: 38 return 39 h = _hash_funcs[method]() 40 if isinstance(password, unicode): 41 password = password.encode('utf-8') 42 h.update(password) 43 return h.hexdigest() 44 45 46 def generate_password_hash(password, method = 'sha1', salt_length = 8): 47 salt = method != 'plain' and gen_salt(salt_length) or '' 48 h = _hash_internal(method, salt, password) 49 if h is None: 50 raise TypeError('invalid method %r' % method) 51 return '%s$%s$%s' % (method, salt, h) 52 53 54 def check_password_hash(pwhash, password): 55 if pwhash.count('$') < 2: 56 return False 57 method, salt, hashval = pwhash.split('$', 2) 58 return _hash_internal(method, salt, password) == hashval