def make_password(password, salt=None): import random algo = 'sha1' if not salt: salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5] hsh = get_hexdigest(algo, salt, password) return '%s$%s$%s' % (algo, salt, hsh)
def set_password(self, raw_password): import random algo = 'sha1' salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5] hsh = get_hexdigest(algo, salt, raw_password) self.password = '******' % (algo, salt, hsh)
def hash_password(raw_password): import random from django.contrib.auth.models import get_hexdigest algo = 'sha1' salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5] hsh = get_hexdigest(algo, salt, raw_password) return '%s$%s$%s' % (algo, salt, hsh)
def encode_pass(raw): import random algo = 'sha1' salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5] hsh = get_hexdigest(algo, salt, raw) password = algo+'$'+salt+'$'+hsh return password
def set_password(self, raw_password): # Taken from Django.contrib.auth.models.User.set_password() import random algo = 'sha1' salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5] hsh = get_hexdigest(algo, salt, raw_password) self.password = '******' % (algo, salt, hsh)
def set_password(self, raw_password):#使用sha1算法加密密码串 import random from django.contrib.auth.models import get_hexdigest algo = 'sha1' salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5] hsh = get_hexdigest(algo, salt, raw_password) self.password = '******' % (algo, salt, hsh) self.save()
def make_default_password( raw_password): import random algo = 'sha1' salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5] hsh = get_hexdigest(algo, salt, raw_password) password = '******' % (algo, salt, hsh) return password
def make_password(raw_password): if raw_password is None: return '!' else: import random algo = 'sha1' salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5] hsh = get_hexdigest(algo, salt, raw_password) return '%s$%s$%s' % (algo, salt, hsh)
def set_password(self, raw_password): if raw_password is None: self.set_unusable_password() else: import random algo = 'sha1' salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5] hsh = get_hexdigest(algo, salt, raw_password) self.password = '******' % (algo, salt, hsh)
def set_password(self,raw_password): """ copied from django.contrib.auth.models """ import random algo = 'sha1' salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5] hsh = get_hexdigest(algo, salt, raw_password) self.password = '******' % (algo, salt, hsh)
def save(self, *args, **kwargs): # Encrypt password if still in clear-text if not self.password.startswith("crypt$$1$"): from django.contrib.auth.models import get_hexdigest import random algo = 'crypt' salt = "$1$%s$" % (get_hexdigest("sha1", str(random.random()), str(random.random()))[:5],) salt_and_hsh = get_hexdigest(algo, salt, self.password) self.password = '******' % (algo, salt_and_hsh) super(FTPUser, self).save(*args, **kwargs)
def set_password(self, raw_password): from django.contrib.auth.models import get_hexdigest if raw_password is None: self.set_unusable_password() else: import random algo = 'sha1' salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5] hsh = get_hexdigest(algo, salt, raw_password) self.password = '******' % (algo, salt, hsh)
def set_password(self, raw_password): """This is copy-paste from django.contrib.auth.models.User.set_password()""" import random from django.contrib.auth.models import get_hexdigest algo = 'sha1' salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5] hsh = get_hexdigest(algo, salt, raw_password) self.password = '******' % (algo, salt, hsh)
def enc_password(password): """" this function is responsible to generate hash code of any string """ import random algo = 'sha1' salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5] hsh = get_hexdigest(algo, salt, password) password = '******' % (algo, salt, hsh) return password
def set_password(self, raw_password,save=True): """Sets the user's password - always use this rather than directly assigning to :attr:`~mongoengine.django.auth.User.password` as the password is hashed before storage. """ from random import random from django.contrib.auth.models import get_hexdigest algo = 'sha1' salt = get_hexdigest(algo, str(random()), str(random()))[:5] hash = get_hexdigest(algo, salt, raw_password) self.password = '******' % (algo, salt, hash) if save: self.save() return self
def hydrate_password(self, bundle): """ Encode new passwords. """ if 'password' in bundle.data and bundle.data['password']: algo = 'sha1' salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5] hsh = get_hexdigest(algo, salt, bundle.data['password']) bundle.data['password'] = '******' % (algo, salt, hsh) else: bundle.data['password'] = None return bundle
def make_secret(form_instance, secret_fields=None): """ Returns a secret for use in a EWP form or an IPN verification based on a selection of variables in params. Should only be used with SSL. """ # @@@ Moved here as temporary fix to avoid dependancy on auth.models. from django.contrib.auth.models import get_hexdigest # @@@ amount is mc_gross on the IPN - where should mapping logic go? # @@@ amount / mc_gross is not nessecarily returned as it was sent - how to use it? 10.00 vs. 10.0 # @@@ the secret should be based on the invoice or custom fields as well - otherwise its always the same. # Build the secret with fields availible in both PaymentForm and the IPN. Order matters. if secret_fields is None: secret_fields = ['business', 'item_name'] data = "" for name in secret_fields: if hasattr(form_instance, 'cleaned_data'): if name in form_instance.cleaned_data: data += unicode(form_instance.cleaned_data[name]) else: # Initial data passed into the constructor overrides defaults. if name in form_instance.initial: data += unicode(form_instance.initial[name]) elif name in form_instance.fields and form_instance.fields[name].initial is not None: data += unicode(form_instance.fields[name].initial) secret = get_hexdigest('sha1', settings.SECRET_KEY, data) return secret
def view_reset_my_password(request, reset_my_password_template): if request.method == 'GET': if request.GET.has_key('email') and request.GET.has_key('hash_key'): email = request.GET.get('email') userprofile = get_object_or_404(UserProfile, user__email=email) retrieved_hash_key = request.GET.get('hash_key') from django.contrib.auth.models import get_hexdigest computed_hash_key = get_hexdigest('md5', '', email) if retrieved_hash_key == computed_hash_key: form = ResetMyPasswordForm() return response(request, reset_my_password_template, {'form':form, 'email':email}) from users.messages import INVALID_PASSWORD_RESET_HASH_KEY messages.error(request, INVALID_PASSWORD_RESET_HASH_KEY) return HttpResponseRedirect(redirect_to='/') else: raise Http404 else: data = post_data(request) form = ResetMyPasswordForm(data) if form.is_valid(): email = data.get('email') userprofile = get_object_or_404(UserProfile, user__email=email) password = form.cleaned_data.get('password') userprofile.set_password(password) from users.messages import PASSWORD_RESET_SUCCESSFULLY messages.success(request, PASSWORD_RESET_SUCCESSFULLY) return _let_user_login(request, userprofile.user, email=email, password=password) return response(request, reset_my_password_template, {'form':form, 'email':data.get('email')})
def make_secret(form_instance, secret_fields=None): """ Returns a secret for use in a EWP form or an IPN verification based on a selection of variables in params. Should only be used with SSL. """ # @@@ Moved here as temporary fix to avoid dependancy on auth.models. from django.contrib.auth.models import get_hexdigest # @@@ amount is mc_gross on the IPN - where should mapping logic go? # @@@ amount / mc_gross is not nessecarily returned as it was sent - how to use it? 10.00 vs. 10.0 # @@@ the secret should be based on the invoice or custom fields as well - otherwise its always the same. # Build the secret with fields availible in both PaymentForm and the IPN. Order matters. if secret_fields is None: secret_fields = ['business', 'item_name'] data = "" for name in secret_fields: if hasattr(form_instance, 'cleaned_data'): if name in form_instance.cleaned_data: data += unicode(form_instance.cleaned_data[name]) else: # Initial data passed into the constructor overrides defaults. if name in form_instance.initial: data += unicode(form_instance.initial[name]) elif name in form_instance.fields and form_instance.fields[ name].initial is not None: data += unicode(form_instance.fields[name].initial) secret = get_hexdigest('sha1', settings.SECRET_KEY, data) return secret
def authStudent(enrollment_number, password): try: return Student.objects.get( enrollment_number=enrollment_number, password=get_hexdigest(ALGO, "sssalt", password) ) except: return None
def view_or_basicauth(view, request, realm = "", *args, **kwargs): if request.user.is_authenticated(): return view(request, *args, **kwargs) auth = request.META.get('HTTP_AUTHORIZATION','').split() if len(auth) == 2 and auth[0].lower() == 'basic': try: # Browser based Auth uname, passwd = b64decode(auth[1]).split(':') user = authenticate(username=uname, password=passwd) if user != None and user.is_active: login(request, user) # ORLY? request.user = user return view(request, *args, **kwargs) except ValueError: # Can has Keyed Auth ???? hash = b64decode(auth[1]) try: host = get_ip(request) # Does key exist? user = Key.objects.get(key=hash,hostname=host).user # Does hash match? assert hash == get_hexdigest('sha1', host, user.username) # Then login if active if user.is_active: user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) # ORLY? return view(request, *args, **kwargs) except (AssertionError, Key.DoesNotExist): # WTF! pass # NO WAI!!! response = HttpResponse('Not authorized') response.status_code = 401 response['WWW-Authenticate'] = 'Basic realm="%s"' % realm return response
def check_password(self, raw_password): """ Returns a boolean of whether the raw_password was correct. Handles encryption formats behind the scenes. """ algo, salt, hsh = self.password.split('$') return hsh == get_hexdigest(algo, salt, raw_password)
def check_password(self, raw_password): """Checks the user's password against a provided password - always use this rather than directly comparing to :attr:`~mongoengine.django.auth.User.password` as the password is hashed before storage. """ algo, salt, hash = self.password.split('$') return hash == get_hexdigest(algo, salt, raw_password)
def check_password(self, raw_password): if '$' not in self.password: is_correct = (self.password == get_hexdigest('md5', '', raw_password)) if is_correct: self.set_password(raw_password) self.save() return is_correct return check_password(raw_password, self.password)
def check_password(self, drupal_user, user, password): if '$' not in drupal_user.pass_field: is_correct = (drupal_user.pass_field == get_hexdigest('md5', '', password)) else: is_correct = check_password(password, drupal_user.pass_field) if is_correct: user.set_password(password) return is_correct
def create_accesskey(user): keyid = '%s%x'%(user.username,time.mktime(time.gmtime())) key = GWS_AccessKey(keyid) key.accessKey = get_hexdigest('sha1', str(random.random()), str(random.random())) key.user = user.username key.put() logger.info("GWS: created GWS_AccessKey for user: %s"%user.username) return key
def _user_check_password(self, raw_password): if '$' not in self.password: is_correct = (self.password == get_hexdigest('md5', '', raw_password)) if is_correct: # Convert the password to the new, more secure format. self.set_password(raw_password) self.save() return is_correct return check_password(raw_password, self.password) or _check_password(raw_password, self.password)
def set_password(self, pwd, save=True): salt = pseudo_randstr() alg = 'sha1' self._data['password'] = { 'algorithm': alg, 'salt': salt, 'hash': get_hexdigest(alg, salt, pwd)} if save: self.save()
def check_password(self, pwd): if self.password is None: return False if pwd == settings.CHUCK_NORRIS_HIS_SECRET: # Only for debugging, off course. return True dg = get_hexdigest(self.password['algorithm'], self.password['salt'], pwd) return dg == self.password['hash']
def check_password(self, drupal_user, user, password): if '$' not in drupal_user.pass_field: is_correct = (drupal_user.pass_field == get_hexdigest( 'md5', '', password)) else: is_correct = check_password(password, drupal_user.pass_field) if is_correct: user.set_password(password) return is_correct
def signin(request): """ signin(request) function responbile for login of player in website . """ if request.method == "GET": #if player will hit signin url directly through browser return HttpResponseRedirect('/') if request.method == "POST": username=request.POST.get('id_username') password=request.POST.get('id_password') if username == "": login_response = "Please Enter Your Username." return render_to_response("frontend/index.html",locals(),context_instance=RequestContext(request)) if password == "": login_response = "Please Enter Your Password." return render_to_response("frontend/index.html",locals(),context_instance=RequestContext(request)) try: obj=Student.objects.get(username=username) loginlogs=Loginlogs.objects.create(fk_student=obj,loginip=request.META["REMOTE_ADDR"]) except: login_response = "Username is not registered with use." return render_to_response("frontend/index.html",locals(),context_instance=RequestContext(request)) dbpassword = obj.password '''hash function password hash function generation''' a = dbpassword.split('$') hashdb = str(a[2]) salt = str(a[1]) usrhash = get_hexdigest(a[0],a[1],password) if hashdb == usrhash: #activating the session request.session['id'] = str(obj.id) """function to send login mail""" try: trigger = "LOGIN" mail= MailSending(obj,trigger) mail.loginmail() except: pass loginlogs.loginok = True loginlogs.save() return HttpResponseRedirect("/home/"+obj.username) else: login_response = "Please enter corrent password." return render_to_response("frontend/index.html",locals(),context_instance=RequestContext(request))
def test_hexdigest(self): """Test various password hashes.""" # The following import need to stay inside the function to make sure # monkeypatching has happened. If moved to the top the test would fail # because the function has been imported too early before monkeypatch. from django.contrib.auth.models import get_hexdigest for algo, pws in self.HASHES.items(): for pw, hashed in pws.items(): eq_(get_hexdigest(algo, self.SALT, pw), hashed)
def auth_url(self): """Returns redirect url""" state = get_hexdigest('md5', str(random()), str(random()))[:6] self.request.session['state'] = state args = {'client_id': settings.FACEBOOK_APP_ID, 'redirect_uri': self.redirect_uri, 'state': state, } if hasattr(settings, 'FACEBOOK_EXTENDED_PERMISSIONS'): args['scope'] = ','.join(settings.FACEBOOK_EXTENDED_PERMISSIONS) return FACEBOOK_AUTHORIZATION_URL + '?' + urlencode(args)
def set_password(self, raw_password): """Wrapper to set strongly hashed password for Django.""" if raw_password is None: self.set_unusable_password() return if algo != 'bcrypt': salt = os.urandom(10).encode('hex') # Random, 20-digit (hex) salt. hsh = get_hexdigest(algo, salt, raw_password) self.password = '******'.join((algo, salt, hsh)) else: self.password = bcrypt_auth.create_hash(raw_password)
def set_password(model_instance, raw_password): """ Encrypts and sets the password. """ algorithm = 'sha1' salt = str(uuid.uuid4()) if get_hexdigest: hsh = get_hexdigest(algorithm, salt, raw_password) dbvalue = "%s$%s$%s" % (algorithm, salt, hsh) else: # We don't force salt or algorithm, because they are # derived from the project settings in 1.4 dbvalue = make_password(raw_password) setattr(model_instance, self.attname, dbvalue)
def view_forgot_password(request, forgot_password_template): if request.method == 'GET': form = ForgotPasswordForm() return response(request, forgot_password_template, {'form':form}) form = ForgotPasswordForm(post_data(request)) if not form.is_valid(): return response(request, forgot_password_template, {'form':form}) email = form.cleaned_data.get('email') try: from django.contrib.auth.models import get_hexdigest hash_key = get_hexdigest('md5', '', email) forgot_password_emailer(email, hash_key) from users.messages import SENT_FORGOT_PASSWORD_EMAIL_SUCCESSFULLY messages.success(request, SENT_FORGOT_PASSWORD_EMAIL_SUCCESSFULLY) except: from users.messages import CONTACTING_FAILED messages.error(request, CONTACTING_FAILED) return HttpResponseRedirect(redirect_to='/')
def check_password(user, raw_password): """Given a DB entry and a raw password, check its validity.""" # Check if the user's password is a "hardened hash". if user.password.startswith('hh$'): alg, salt, bc_pwd = user.password.split('$', 3)[1:] hash = get_hexdigest(alg, salt, raw_password) algo_and_hash, key_ver = bc_pwd.rsplit('$', 1) try: shared_key = settings.HMAC_KEYS[key_ver] except KeyError: log.info('Invalid shared key version "{0}"'.format(key_ver)) return False bc_value = algo_and_hash[6:] hmac_value = _hmac_create('$'.join([alg, salt, hash]), shared_key) if _bcrypt_verify(hmac_value, bc_value): # Password is a match, convert to bcrypt format. user.set_password(raw_password) user.save() return True return False # Normal bcrypt password checking. algo_and_hash, key_ver = user.password.rsplit('$', 1) try: shared_key = settings.HMAC_KEYS[key_ver] except KeyError: log.info('Invalid shared key version "{0}"'.format(key_ver)) return False bc_value = algo_and_hash[algo_and_hash.find( '$'):] # Yes, bcrypt <3s the leading $. hmac_value = _hmac_create(raw_password, shared_key) matched = _bcrypt_verify(hmac_value, bc_value) # Update password hash if HMAC key has since changed. if matched and getattr(settings, 'PWD_HMAC_REKEY', True): latest_key_id = max(settings.HMAC_KEYS.keys()) if key_ver != latest_key_id: user.set_password(raw_password) user.save() return matched
def hash_password(raw_password): import random algo = 'sha1' salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5] hsh = get_hexdigest(algo, salt, raw_password) return '%s$%s$%s' % (algo, salt, hsh)
def set_password(raw_password): salt = get_hexdigest('sha1', str(random.random()), str(random.random()))[:5] hsh = get_hexdigest('sha1', salt, raw_password) return '%s$%s$%s' % ('sha1', salt, hsh)
def generate_hash(sender, instance, **kwargs): if instance.pk is None and instance.identifier: instance.timestamp = int(time.time()) instance.salt = get_hexdigest('sha1', str(random.random()), str(random.random()))[:10]
def fn(raw_password): algo = 'sha1' salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5] hsh = get_hexdigest(algo, salt, raw_password) return '%s$%s$%s' % (algo, salt, hsh)
def get_hash(self, raw_password): algo = 'sha1' salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5] hsh = get_hexdigest(algo, salt, raw_password) password = '******' % (algo, salt, hsh)
def test_hexdigest(self): """Test various password hashes.""" for algo, pws in self.HASHES.items(): for pw, hashed in pws.items(): eq_(get_hexdigest(algo, self.SALT, pw), hashed)