def sign_value(value, expiry_delay=SIGNATURE_EXPIRY_INTERVAL): expiry_time = int(time.time()) + expiry_delay plaintext = ':'.join([settings.SECRET_KEY, str(expiry_time), str(value)]) return "%d,%s" % (expiry_time, hash_func(plaintext).hexdigest())
def fill_entropy_pool(self, reddit_limit: Optional[int] = 10) -> None: """ Makes a call to Reddit to gather n number of posts, then hashes the subreddit names in chunks of five to generate entropy. :param reddit_limit: The number of posts to return from /r/all/new :return: Nothing. """ if self.entropy_avail == self.pool_size: return url = '{}/r/all/new'.format(self.url) r = requests.get(url, params={'limit': reddit_limit}, headers=self.headers) posts = r.json()['data']['children'] offset = 0 while offset < reddit_limit: end = offset + 5 if end > reddit_limit: end -= reddit_limit b_str = ''.join([ posts[i]['data']['subreddit'] for i in range(offset, end) ]).encode() for byte in hash_func(b_str).digest(): if self.entropy_avail + 8 <= self.pool_size: self.dev_random.append(byte) self.entropy_avail += 8 offset += 5
def login(request): if request.method != "POST": return render_to_response('general/login.html',{'page':'login'},RequestContext(request)) request.session.set_test_cookie() if request.session.test_cookie_worked(): request.session.delete_test_cookie() else: return HttpResponse("Please enable cookies and try again") input_email = str(request.POST['email']) input_pwd = hash_func(str(request.POST['pwd'])).hexdigest() login_tuple = Login.objects.all().filter(email=input_email) error_msg = "" if login_tuple: actual_pwd = str(login_tuple[0].password) if input_pwd == actual_pwd: request.session['loggedinside'] = True request.session['email'] = input_email request.session.set_expiry(0) #Redirect to home page, but Logged in return render_to_response("general/home.html",{},RequestContext(request)) else: error_msg = 'Please enter the right email/password combination' else: error_msg = 'Please enter the right email/password combination' return render_to_response('general/login.html',{'error_msg': error_msg},context_instance=RequestContext(request))
def get_modification_signature(self, expiry_delay=STORY_MODIFICATION_SIGNATURE_EXPIRY_INTERVAL): expiry_time = int(time.time()) + expiry_delay assert self.id, "Cannot generate signature for an unsaved story." plaintext = ':'.join([settings.SECRET_KEY, str(expiry_time), str(self.id)]) return "%d,%s" % (expiry_time, hash_func(plaintext).hexdigest())
def fetch_cached(url, params=None, **kwargs): cache_key = hash_func((url + repr(params)).encode('utf-8')).hexdigest() cache_file = path.join(CACHE_DIR, cache_key) if path.exists(cache_file): with open(cache_file, mode="rb") as fd: return fd.read() else: res = requests.get(url, params, **kwargs) with open(cache_file, mode="wb+") as fd: fd.write(res.content) return res.content
def sign(self, ignore_head=True, ignore_files=True, ignore_tracks=True): """ calculate disc (rip) signature (as binary string) :param ignore_head: :param ignore_files: :param ignore_tracks: :return: """ # from head if ignore_head: _1 = '' else: _head = ('%03d' % len(self.files), '%03d' % len(self.tracks), self.performer, self.title) _1 = (''.join([_.lower().encode('utf-8') for _ in _head])).replace(' ', '') # # from files if ignore_files: _2 = '' else: _2 = (''.join([_.name.lower().encode('utf-8') for _ in self.files])).replace(' ', '') # # from tracks _3 = '' _4 = "%02X" % len(self.tracks) for trk in self.tracks: if not ignore_tracks: _3 += trk.title.lower().encode('utf-8') # _4 += ',' + '.'.join(["%06X" % _.time for _ in trk.indexes]) # _3 = _3.replace(' ', '') h = hash_func() for _ in (_1, _2, _3, _4): h.update(_) # # print(_1) # print(_2) # print(_3) # print(_4) return h.digest()
def check_signed_value(value, sig): parts = str(sig).split(",", 1) # split only once if len(parts) != 2: return False expiry_time = parts[0] sigdigest = parts[1] if int(expiry_time) < time.time(): return False plaintext = ':'.join([settings.SECRET_KEY, str(expiry_time), str(value)]) return hash_func(plaintext).hexdigest() == sigdigest
def registeruser(request): try: if logged_in(request): raise Http404() context_instance=RequestContext(request) if request.method == 'POST': login_form = LoginForm(request.POST) recaptcha_challenge_field = request.POST['recaptcha_challenge_field'] recaptcha_response_field = request.POST['recaptcha_response_field'] recaptcha_remote_ip = "" captcha_is_correct = check_captcha(recaptcha_challenge_field, recaptcha_response_field, recaptcha_remote_ip) login_is_valid = login_form.is_valid() if login_is_valid and captcha_is_correct: cleaned_login_data = login_form.cleaned_data cleaned_password = hash_func(cleaned_login_data['password']).hexdigest() cleaned_email = cleaned_login_data['email'] login_instance = Login(cleaned_email, cleaned_password) login_instance.save() sendmail_after_userreg(cleaned_email, cleaned_login_data['password']) notify_new_user(cleaned_email) return HttpResponseRedirect('/register/user/success/') else: captcha = 'true' if not captcha_is_correct: captcha = 'false' return render_to_response('register/registeruser.html', {'login_form':login_form, 'page':'register', 'captcha':captcha}, RequestContext(request)) return render_to_response('register/registeruser.html', {'login_form' : LoginForm(), 'page':'register'}, RequestContext(request)) except KeyError: return error_key(request)
def test_modification_signature(self, sig): """Tests a putative mod-signature for this object, retuning True iff it is valid.""" parts = str(sig).split(",") if len(parts) != 2: return False expiry_time = parts[0] sigdigest = parts[1] if int(expiry_time) < time.time(): return False plaintext = ':'.join([settings.SECRET_KEY, str(expiry_time), str(self.id)]) return hash_func(plaintext).hexdigest() == sigdigest
def add_response(self, cursor): getpassword = tornado.escape.xhtml_escape(self.get_argument("password")) getpassword = hash_func(getpassword).hexdigest(); results = cursor.fetchall() passwordfromdb = '' if results: passwordfromdb = results[0] try: if str(passwordfromdb[0]) == str(getpassword): self.set_secure_cookie("user", self.get_argument("username")) self.set_secure_cookie("incorrect", "0") self.redirect("/") else: incorrect = self.get_secure_cookie("incorrect") if not incorrect: incorrect = 0 self.set_secure_cookie("incorrect", str(int(incorrect) + 1)) # self.write('<center>Something Wrong With Your Data <a href="/">Go Home</a></center>') self.redirect("/login") except IndexError: incorrect = self.get_secure_cookie("incorrect")
def newregister(request): """ Make a new registration, inserting into User_info and ProfileImage models. """ try: # If the user is already loggedin never show the login page if logged_in(request): return render_to_response('register/logged_in.html', RequestContext(request)) # Upon Register button click if request.method == 'POST': form = NewRegisterForm(request.POST, request.FILES) # Form has all valid entries if form.is_valid(): cleaned_reg_data = form.cleaned_data inp_username = cleaned_reg_data['username'] inp_password = cleaned_reg_data['password'] inp_email = cleaned_reg_data['email'] # Saving the user inputs into table new_register = form.save(commit=False) new_register.password = hash_func(inp_password) \ .hexdigest() new_register.save() user_object = get_object_or_404(User_info, \ username=inp_username) # Optional image upload processing and saving if 'image' in request.FILES: profile_image = request.FILES['image'] profile_image_object = ProfileImage \ (image=profile_image, \ username=user_object) profile_image_object.image.name = inp_username + \ ".jpg" profile_image_object.save() # Setting the session variables request.session['username'] = cleaned_reg_data['username'] request.session['is_loggedin'] = True request.session['email'] = cleaned_reg_data['email'] sendmail_after_userreg(inp_username, inp_password, inp_email) notify_new_user(inp_username, inp_email) return render_to_response('register/register_success.html', {'is_loggedin':logged_in(request), \ 'username':request.session['username']}, \ RequestContext(request)) # Invalid form inputs else: error = "Invalid inputs" return render_to_response('register/newregister.html', { 'form': form, 'error': error }, RequestContext(request)) return render_to_response('register/newregister.html', {'form': NewRegisterForm}, RequestContext(request)) except KeyError: return error_key(request)
def dict_hash(p_dict): hashee = json.dumps(p_dict, sort_keys=True) return hash_func(hashee.encode('ascii')).hexdigest()
#!/usr/bin/python from hashlib import sha512 as hash_func import getpass raw_pass1 = getpass.getpass( "Enter the new password: "******"Enter the same again: " ); if raw_pass1 == raw_pass2: hashed_password = hash_func(raw_pass1).hexdigest() print hashed_password else: print "Please enter the same password twice"
def newregister(request): """ Make a new registration, inserting into User_info and ProfileImage models. """ try: # If the user is already loggedin never show the login page if logged_in(request): return render_to_response('register/logged_in.html', RequestContext(request)) # Upon Register button click if request.method == 'POST': form = NewRegisterForm(request.POST, request.FILES) # Form has all valid entries if form.is_valid(): cleaned_reg_data = form.cleaned_data inp_username = cleaned_reg_data['username'] inp_password = cleaned_reg_data['password'] inp_email = cleaned_reg_data['email'] # Saving the user inputs into table new_register = form.save(commit=False) new_register.password = hash_func(inp_password) \ .hexdigest() new_register.save() user_object = get_object_or_404(User_info, \ username=inp_username) # Optional image upload processing and saving if 'image' in request.FILES: profile_image = request.FILES['image'] profile_image_object = ProfileImage \ (image=profile_image, \ username=user_object) profile_image_object.image.name = inp_username + \ ".jpg" profile_image_object.save() # Setting the session variables request.session['username'] = cleaned_reg_data['username'] request.session['is_loggedin'] = True request.session['email'] = cleaned_reg_data['email'] sendmail_after_userreg(inp_username, inp_password, inp_email) notify_new_user(inp_username, inp_email) return render_to_response('register/register_success.html', {'is_loggedin':logged_in(request), \ 'username':request.session['username']}, \ RequestContext(request)) # Invalid form inputs else: error = "Invalid inputs" return render_to_response('register/newregister.html', {'form': form, 'error':error}, RequestContext(request)) return render_to_response('register/newregister.html', {'form': NewRegisterForm}, RequestContext(request)) except KeyError: return error_key(request)
def hash(value, chars=None): 'Get N chars (default: all) of secure hash hexdigest of value.' value = hash_func(value).hexdigest() if chars: value = value[:chars] return mark_safe(value)
def change_password(request): """ A view to change the password of a logged in user """ try: is_loggedin, username = get_session_variables(request) if not is_loggedin: return HttpResponseRedirect("/register/login") # POST request if request.method == 'POST': form = ChangePasswordForm(request.POST) # Form inputs are valid if form.is_valid(): new_pass = request.POST['new_password'] old_password = hash_func(request.POST['old_password']) \ .hexdigest() new_password = hash_func(request.POST['new_password']) \ .hexdigest() confirm_new_password = hash_func( request.POST['confirm_new_password']) \ .hexdigest() user_data = User_info.objects.get(username = username) actual_pwd = user_data.password # Given current and stored passwords same if old_password == actual_pwd: # New and current passwords user provided are not same if new_password != actual_pwd: # Repass and new pass are same if new_password == confirm_new_password: user_data.password = new_password sendmail_after_pass_change( \ username, \ new_pass, \ user_data.email) user_data.save() return render_to_response( \ 'register/pass_success.html', {'username': username, \ 'is_loggedin': is_loggedin}, \ RequestContext(request)) # Repass and new pass are not same else: error = "New passwords doesn't match" return render_to_response( \ 'register/change_password.html', {'form':form, \ 'username' :username, \ 'is_loggedin':is_loggedin, \ 'error':error}, \ RequestContext(request)) # New and current password user provided are same else: error = "Your old and new password are same. Please \ choose a different password" return render_to_response( \ 'register/change_password.html', {'form':form, \ 'username':username, \ 'is_loggedin':is_loggedin, \ 'error':error}, \ RequestContext(request)) # Given current and stored passwords are not same else: error = "Current password and given password doesn't match" return render_to_response( \ 'register/change_password.html', {'form':form, \ 'username':username, \ 'is_loggedin':is_loggedin, \ 'error':error}, \ RequestContext(request)) # Form inputs is/are invalid else: form = ChangePasswordForm() return render_to_response( \ 'register/change_password.html', {'form':form, \ 'username':username, \ 'is_loggedin':is_loggedin}, \ RequestContext(request)) return render_to_response( \ 'register/change_password.html', {'username': username, \ 'is_loggedin': is_loggedin}, \ RequestContext(request)) except KeyError: return error_key(request)
def login(request): """ A view to evaluate login form """ try: # If the user is already loggedin never show the login page if logged_in(request): return render_to_response('register/logged_in.html', \ RequestContext(request)) # Upon signin button click if request.method=='POST': form = LoginForm(request.POST) # Form has all valid entries if form.is_valid(): cleaned_login_data = form.cleaned_data inp_username = cleaned_login_data['username'] inp_password = cleaned_login_data['password'] hashed_password = hash_func(inp_password).hexdigest() user_tuple = User_info.objects.all().filter \ (username = inp_username) # There exist an entry in table with the given username if user_tuple: actual_pwd = user_tuple[0].password # Password matches: session validation if actual_pwd == hashed_password: request.session['is_loggedin'] = True request.session['username'] = inp_username request.session['email'] = user_tuple[0].email return HttpResponseRedirect('/') # Invalid password else: error = "Invalid password. Is it really you, " + \ str(inp_username) + "?" return render_to_response('register/login.html', \ {'form':form, 'error':error}, RequestContext(request)) # There's no entry in the table with the given username else: error = "User doesn't exist!" return render_to_response('register/login.html', \ {'form':form, 'error':error}, RequestContext(request)) # Invalid form inputs else: error = "Invalid username and password" return render_to_response('register/login.html', {'form':form, 'error':error}, RequestContext(request)) # 'GET' request i.e refresh else: # User is logged in and hence redirect to home page if 'is_loggedin' in request.session and \ request.session['is_loggedin']: return HttpResponseRedirect('/') # User is not logged in and refresh the page else: form=LoginForm() return render_to_response('register/login.html', {'form':form}, RequestContext(request)) except KeyError: return error_key(request)
def hash_it (self, s): return hash_func(s).hexdigest()
def login(request): """ A view to evaluate login form """ try: # If the user is already loggedin never show the login page if logged_in(request): return render_to_response('register/logged_in.html', \ RequestContext(request)) # Upon signin button click if request.method == 'POST': form = LoginForm(request.POST) # Form has all valid entries if form.is_valid(): cleaned_login_data = form.cleaned_data inp_username = cleaned_login_data['username'] inp_password = cleaned_login_data['password'] hashed_password = hash_func(inp_password).hexdigest() user_tuple = User_info.objects.all().filter \ (username = inp_username) # There exist an entry in table with the given username if user_tuple: actual_pwd = user_tuple[0].password # Password matches: session validation if actual_pwd == hashed_password: request.session['is_loggedin'] = True request.session['username'] = inp_username request.session['email'] = user_tuple[0].email return HttpResponseRedirect('/') # Invalid password else: error = "Invalid password. Is it really you, " + \ str(inp_username) + "?" return render_to_response('register/login.html', \ {'form':form, 'error':error}, RequestContext(request)) # There's no entry in the table with the given username else: error = "User doesn't exist!" return render_to_response('register/login.html', \ {'form':form, 'error':error}, RequestContext(request)) # Invalid form inputs else: error = "Invalid username and password" return render_to_response('register/login.html', { 'form': form, 'error': error }, RequestContext(request)) # 'GET' request i.e refresh else: # User is logged in and hence redirect to home page if 'is_loggedin' in request.session and \ request.session['is_loggedin']: return HttpResponseRedirect('/') # User is not logged in and refresh the page else: form = LoginForm() return render_to_response('register/login.html', {'form': form}, RequestContext(request)) except KeyError: return error_key(request)
def change_password(request): """ A view to change the password of a logged in user """ try: is_loggedin, username = get_session_variables(request) if not is_loggedin: return HttpResponseRedirect("/register/login") # POST request if request.method == 'POST': form = ChangePasswordForm(request.POST) # Form inputs are valid if form.is_valid(): new_pass = request.POST['new_password'] old_password = hash_func(request.POST['old_password']) \ .hexdigest() new_password = hash_func(request.POST['new_password']) \ .hexdigest() confirm_new_password = hash_func( request.POST['confirm_new_password']) \ .hexdigest() user_data = User_info.objects.get(username=username) actual_pwd = user_data.password # Given current and stored passwords same if old_password == actual_pwd: # New and current passwords user provided are not same if new_password != actual_pwd: # Repass and new pass are same if new_password == confirm_new_password: user_data.password = new_password sendmail_after_pass_change( \ username, \ new_pass, \ user_data.email) user_data.save() return render_to_response( \ 'register/pass_success.html', {'username': username, \ 'is_loggedin': is_loggedin}, \ RequestContext(request)) # Repass and new pass are not same else: error = "New passwords doesn't match" return render_to_response( \ 'register/change_password.html', {'form':form, \ 'username' :username, \ 'is_loggedin':is_loggedin, \ 'error':error}, \ RequestContext(request)) # New and current password user provided are same else: error = "Your old and new password are same. Please \ choose a different password" return render_to_response( \ 'register/change_password.html', {'form':form, \ 'username':username, \ 'is_loggedin':is_loggedin, \ 'error':error}, \ RequestContext(request)) # Given current and stored passwords are not same else: error = "Current password and given password doesn't match" return render_to_response( \ 'register/change_password.html', {'form':form, \ 'username':username, \ 'is_loggedin':is_loggedin, \ 'error':error}, \ RequestContext(request)) # Form inputs is/are invalid else: form = ChangePasswordForm() return render_to_response( \ 'register/change_password.html', {'form':form, \ 'username':username, \ 'is_loggedin':is_loggedin}, \ RequestContext(request)) return render_to_response( \ 'register/change_password.html', {'username': username, \ 'is_loggedin': is_loggedin}, \ RequestContext(request)) except KeyError: return error_key(request)
def hash_it(self, s): return hash_func(s).hexdigest()
def __init__(self, password, length=40): self.fireword = self._get_mingleword(str(hash_func(password.encode("utf-8")).hexdigest()))[:length]