def login_handle(request): from hashlib import sha1 flage = True context = {} user = None if request.method == 'POST': dict = request.POST user_name = dict.get('username', '') pwd = dict.get('pwd') # 加密 sha1 = sha1() sha1.update(pwd) pwd = sha1.hexdigest() rember_me = dict.get('rember_me', 0) # 检查用户名输入是否正确 uname_err_code = check_user_for_login(user_name) if uname_err_code > 0: flage = False context['uname_err_code'] = uname_err_code context['uname'] = user_name else: context['uname_err_code'] = 0 # 正确返回0 # 检查密码是否正确 if user_name: if uname_err_code == 0: user = Users.objects.filter(uname=user_name) pword = user[0].pword if pword != pwd: flage = False context['pwd_err_code'] = 1 else: context['pwd_err_code'] = 0 else: context['uname_err_code'] = 3 context['pwd_err_code'] = 0 else: context['uname_err_code'] = 1 context['pwd_err_code'] = 0 # 如果登陆成功跳转到首页, 否则返回错误信息 if flage: url = request.COOKIES.get('url', '/user/') red = HttpResponseRedirect(url) # 成功后删除转向地址,防止以后直接登录造成的转向 red.set_cookie('url', '', max_age=-1) if rember_me: red.set_cookie('uname', user_name) else: red.set_cookie('uname', '', max_age=-1) request.session['user_id'] = user[0].id request.session['user_name'] = user_name return red # return redirect('/user/') else: return render(request, 'Users/login.html', context)
def get_hash(filename): try: sha1 = hashlib.sha1() with open(filename,'rb') as f: for chunk in iter(lambda: f.read(8192), b''): sha1.update(chunk) return sha1.digest() except IOError: return None
def _sha1_file(filename, block_size=65536): import hashlib sha1 = hashlib.sha1() f = open(filename, 'rb') while True: chunk = f.read(block_size) if not chunk: break sha1.update(chunk) return sha1.hexdigest()
def get_hash(file_name) -> Tuple: BUF_SIZE = 65536 # ground to 65535 with open(file_name, "rb") as f: while True: data = f.read(BUF_SIZE) if not data: break md5.update(data) sha1.update(data) return (md5.hexdigest(), sha1.hexdigest())
def sha1_file(file, block_size=2**20): f = open(file, 'rb') sha1 = get_sha1_obj() while True: data = f.read(block_size) if not data: break sha1.update(data) f.close() return sha1.hexdigest()
def register_handle(request): from hashlib import sha1 flage = True context = {} if request.method == 'POST': # 获取输入的内容 dict = request.POST user_name = dict.get('user_name') pwd = dict.get('pwd') cpwd = dict.get('cpwd') email = dict.get('email') # 检查用户名输入是否正确 uname_err_code = check_user_name(user_name) if uname_err_code > 0: flage = False context['uname_err_code'] = uname_err_code else: context['uname_err_code'] = 0 # 正确返回0 # 检查密码是否正确 if pwd != cpwd: flage = False context['pwd_err_code'] = 1 # 错误返回1 else: context['pwd_err_code'] = 0 # 正确返回0 # 如果用户名和密码都正确,则提交到数据库 if flage: user = Users() user.uname = user_name # 加密 sha1 = sha1() sha1.update(pwd) pwd = sha1.hexdigest() user.pword = pwd user.email = email user.save() return redirect('/user/login/') else: # 否则将错误信息返回给前台页面 return render(request, 'Users/register.html', context)
def hash_file(filepath: Path) -> str: """Opens the file at filepath and calculates its SHA1 hash Taken from https://stackoverflow.com/a/22058673 Args: filepath (pathlib.Path): Path to file Returns: str: SHA1 hash """ import hashlib # Let's read stuff in 64kB chunks BUF_SIZE = 65536 sha1 = hashlib.sha1() with open(filepath, "rb") as f: while True: data = f.read(BUF_SIZE) if not data: break sha1.update(data) return sha1.hexdigest()
def _gen_fingerprint(self, request): from hashlib import sha1 import w3lib.url # 1. 获取请求进来的数据 url = request.url method = request.method params = request.params data = request.data """对进来的参数进行处理""" # 1. url查询字符串规整 url = w3lib.url.canonicalize_url(url) # 2. 请求方法字符串统一转为大写 method = method.upper() # 3.处理params字符串, 因为update只仅仅接收字符串 # 增加判断是否有提交的内容 params = params if params is not None else {} params = str(sorted(params.items())) # 4. 处理data字符串 data = data if data is not None else {} data = str(sorted(data.items())) # 构建一个sha1对象 sha1 = sha1() # update() 必须接受一个非Unicode字符串 # utf8_str方法, 1)过滤非Unicode的字符串 2)将Unicode的字符串转成utf-8的字符串 sha1.update(self.utf8_str(url)) sha1.update(self.utf8_str(method)) sha1.update(self.utf8_str(params)) sha1.update(self.utf8_str(data)) # *** 生成16进制数的sha1的值 fp = sha1.hexdigest() return fp
def _gen_fingerprint(self, request): from hashlib import sha1 import w3lib.url url = request.url method = request.method params = request.params data = request.data # url查询字符串规整 url = w3lib.url.canonicalize_url(url) # 请求方法字符串统一转为大写 method = method.upper() # 处理params为字符串 params = params if params is not None else {} params = str(sorted(params.items())) # 处理data为字符串 data = data if data is not None else {} data = str(sorted(data.items())) # 构建一个sha1对象 sha1 = sha1() # update() 必须接收一个非Unicode字符串(Python2 str / Python3 bytes) sha1.update(self.utf8_str(url)) sha1.update(self.utf8_str(method)) sha1.update(self.utf8_str(params)) sha1.update(self.utf8_str(data)) # 生成16进制数的sha1值 fp = sha1.hexdigest() return fp
if __name__ == "__main__": parser = OptionParser() parser.add_option("-f", "--comment-file", dest="commentFile") parser.add_option("-c", "--comment", dest="commentText") (options, args) = parser.parse_args() inputFile = args[0] outputFile = args[1] md5 = md5() sha1 = sha1() with open(inputFile, "rb") as inFile: for bytes in inFile: md5.update(bytes) sha1.update(bytes) comment = "" if options.commentText: if options.commentText != "--": comment = "<p>%s</p>" % options.commentText else: comment = "<p>%s</p>" % sys.stdin.read() elif options.commentFile: with open(options.commentFile, "r") as commentFile: commentLines = (line for line in commentFile if not line.lstrip().startswith("#")) # delete comments commentLines = itertools.imap(string.strip, commentLines) # remove redundant whitespace commentLines = itertools.ifilter(None, commentLines) # delete blank lines commentLines = (s[0].upper() + s[1:] for s in commentLines) # ensure first letter is capital commentLines = (s + ("." if s[-1] not in ".!?" else "") for s in commentLines if s) # ensure final punctuatiuon
except OSError, e: if errno.ENOENT == e.errno: os.unlink(pathname) # Remove empty directories. For any that hang around, match their # access and modification times to the source in `/usr/local`, otherwise # the hash of the tarball will not be deterministic. for dirpath, dirnames, filenames in os.walk(tmpname, topdown=False): try: os.rmdir(dirpath) except OSError: os.utime(dirpath, (s.st_atime, s.st_mtime)) # If the shallow copy of `/usr/local` still exists, create a tarball # named by its SHA1 sum and include it in the blueprint. try: try: tar = tarfile.open('usr-local.tar', 'w') tar.add(tmpname, '.') except OSError: return finally: tar.close() sha1 = sha1() f = open('usr-local.tar', 'r') [sha1.update(buf) for buf in iter(lambda: f.read(4096), '')] f.close() tarname = '%s.tar' % (sha1.hexdigest()) os.rename('usr-local.tar', tarname) b.sources['/usr/local'] = tarname
def _getSHA1(self, data): sha1 = hashlib.sha1() sha1.update(data) return sha1.digest()
def hash_files(self, files): sha1 = hashlib.sha1() for file in files: hash, mtime = self._get_key(file) sha1.update(str(hash)) return sha1.hexdigest()
# dir(<module_name>) -- list content "names" defined by module import math # import entire modure from os import walk # import singe "name" (function/submodule) from os import path from math import pi as PI from hashlib import sha1 as hasher # import name with synonym print("Sqrt: ", math.sqrt(9)) print("Traversal:") for _, _, files in walk(".."): print("\t", files) hasher = hasher() hasher.update(b"chunk1") hasher.update(b"chunk2") hasher.update("chunk3".encode('utf-8')) print(hasher.hexdigest()) # to get encoding of file, use encoding method # with open(filename) as f: # print(f.encoding) # to open file with binary mode, use mode = 'rb' # with open(filename, mode='rb') as f: # hasher = hasher() # hasher.update(f.read(1024)) # return hasher.digest() # digest of first min(1024, filesize) bytes of # file
# dir(<module_name>) -- list content "names" defined by module import math # import entire module from os import walk # import single "name" (function/submodule) from os import path from math import pi as PI from hashlib import sha1 as hasher # import name with synonym print("Sqrt: ", math.sqrt(9)) print("Traversal:") for _, _, files in walk(".."): print("\t", files) hasher = hasher() hasher.update(b"chunk1") hasher.update(b"chunk2") hasher.update("chunk3".encode('utf-8')) print(hasher.hexdigest()) # to get encoding of file, use encoding method # with open(filename) as f: # print(f.encoding) # to open file with binary mode, use mode = 'rb' # with open(filename, mode='rb') as f: # hasher = hasher() # hasher.update(f.read(1024)) # return hasher.digest() # digest of first min(1024, filesize) bytes of # file
# -*- coding:utf-8 -*- import RedisHelper from MysqlHelper import mysql from hashlib import sha1 name = raw_input("请输入用户名:") pwd = raw_input("请输入密码:") sha1 = hashlib.sha1() sha1.update(pwd) pwd1 = sha1.hexdigest() try: redis = RedisHelper() if redis.get('uname') == name: print 'ok' else: mysql = MysqlHelper('127.0.0.1', 3306, 'test1', 'root', 'mysql') upwd = mysql.get_one('select upwd from userinfos where uname=%s', [name]) if upwd == None: print '用户名错误' elif upwd[0] == pwd1: redis.set('uname', name) print '登录成功' else: print "密码错误" except Exception, e: print e.message