我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用hashlib.md5()。
def render_navtree(navtree_data, node_template=None, load=False): load = load and 'true' or 'false' if node_template is None: node_template = '''<a href="{{href}}">{{title}}</a>''' m = md5() m.update(node_template + str(random.randrange(0, 100))) template_md5 = m.hexdigest() return '''<div id="nav_%(md5)s" class="navtree" kssattr:templ="templ_%(md5)s"> <script type="text/javascript"> var templ_%(md5)s = Handlebars.compile('%(template)s'); $('#nav_%(md5)s').html(render_navtree(%(json)s, templ_%(md5)s, %(load)s)); </script> </div> ''' % {'md5': template_md5, 'template': node_template.replace('\'', '\\\'').replace('\n', r'\n').replace('\r', r'\r'), 'json': json.dumps(navtree_data), 'load': load, }
def userTwo(hash, tipo, user): global word try: f = open(options.wl) for pwd in f.readlines(): pwd = pwd.strip() if(tipo == 0): d = hashlib.md5(options.salt+hashlib.md5(pwd).hexdigest()+user).hexdigest() else: d = hashlib.sha1(options.salt+hashlib.sha1(pwd).hexdigest()+user).hexdigest() if(d == hash): print word+"(salt+"+ word +"(pass)+user)\t[+] Senha encontrada: "+pwd return print word+"(salt+"+ word +"(pass)+user)\t[-] Senha nao encontrada! :-(" except IOError: print "Nao foi possivel abrir sua wordlist, tente novamente." except Exception as e: print "Erro: "+str(e)
def userOne(hash, tipo, user): global word try: f = open(options.wl) for pwd in f.readlines(): pwd = pwd.strip() if(tipo == 0): d = hashlib.md5(options.salt+pwd+user).hexdigest() else: d = hashlib.sha1(options.salt+pwd+user).hexdigest() if(d == hash): print word+"(salt+pass+user)\t\t[+] Senha encontrada: "+pwd return print word+"(salt+pass+user)\t\t[-] Senha nao encontrada! :-(" except IOError: print "Nao foi possivel abrir sua wordlist, tente novamente." except Exception as e: print "Erro: "+str(e) #With Salt
def saltNine(hash, tipo): global word try: f = open(options.wl) for pwd in f.readlines(): pwd = pwd.strip() if(tipo == 0): d = hashlib.md5(options.salt+hashlib.md5(hashlib.md5(pwd).hexdigest()+options.salt).hexdigest()).hexdigest() else: d = hashlib.sha1(options.salt+hashlib.sha1(hashlib.sha1(pwd).hexdigest()+options.salt).hexdigest()).hexdigest() if(d == hash): print word+"(salt+"+ word +"("+ word +"(pass)+salt))\t[+] Senha encontrada: "+pwd return print word+"(salt+"+ word +"("+ word +"(pass)+salt))\t[-] Senha nao encontrada! :-(" except IOError: print "Nao foi possivel abrir sua wordlist, tente novamente." except Exception as e: print "Erro: "+str(e)
def saltEight(hash, tipo): global word try: f = open(options.wl) for pwd in f.readlines(): pwd = pwd.strip() if(tipo == 0): d = hashlib.md5(options.salt+hashlib.md5(options.salt+pwd).hexdigest()).hexdigest() else: d = hashlib.sha1(options.salt+hashlib.sha1(options.salt+pwd).hexdigest()).hexdigest() if(d == hash): print word+"(salt+"+ word +"(salt+pass))\t[+] Senha encontrada: "+pwd return print word+"(salt+"+ word +"(salt+pass))\t[-] Senha nao encontrada! :-(" except IOError: print "Nao foi possivel abrir sua wordlist, tente novamente." except Exception as e: print "Erro: "+str(e)
def saltSeven(hash, tipo): global word try: f = open(options.wl) for pwd in f.readlines(): pwd = pwd.strip() if(tipo == 0): d = hashlib.md5(options.salt+hashlib.md5(pwd+options.salt).hexdigest()).hexdigest() else: d = hashlib.sha1(options.salt+hashlib.sha1(pwd+options.salt).hexdigest()).hexdigest() if(d == hash): print word+"(salt+"+ word +"(pass+salt))\t[+] Senha encontrada: "+pwd return print word+"(salt+"+ word +"(pass+salt))\t[-] Senha nao encontrada! :-(" except IOError: print "Nao foi possivel abrir sua wordlist, tente novamente." except Exception as e: print "Erro: "+str(e)
def saltFive(hash, tipo): global word try: f = open(options.wl) for pwd in f.readlines(): pwd = pwd.strip() if(tipo == 0): d = hashlib.md5(options.salt+hashlib.md5(pwd).hexdigest()).hexdigest() else: d = hashlib.sha1(options.salt+hashlib.sha1(pwd).hexdigest()).hexdigest() if(d == hash): print word+"(salt+"+ word +"(pass))\t\t[+] Senha encontrada: "+pwd return print word+"(salt+"+ word +"(pass))\t\t[-] Senha nao encontrada! :-(" except IOError: print "Nao foi possivel abrir sua wordlist, tente novamente." except Exception as e: print "Erro: "+str(e)
def saltFour(hash, tipo): global word try: f = open(options.wl) for pwd in f.readlines(): pwd = pwd.strip() if(tipo == 0): d = hashlib.md5(options.salt+pwd+options.salt).hexdigest() else: d = hashlib.sha1(options.salt+pwd+options.salt).hexdigest() if(d == hash): print word+"(salt+pass+salt)\t\t[+] Senha encontrada: "+pwd return print word+"(salt+pass+salt)\t\t[-] Senha nao encontrada! :-(" except IOError: print "Nao foi possivel abrir sua wordlist, tente novamente." except Exception as e: print "Erro: "+str(e)
def saltThree(hash, tipo): global word try: f = open(options.wl) for pwd in f.readlines(): pwd = pwd.strip() if(tipo == 0): d = hashlib.md5(pwd+options.salt+pwd).hexdigest() else: d = hashlib.sha1(pwd+options.salt+pwd).hexdigest() if(d == hash): print word+"(pass+salt+pass)\t\t[+] Senha encontrada: "+pwd return print word+"(pass+salt+pass)\t\t[-] Senha nao encontrada! :-(" except IOError: print "Nao foi possivel abrir sua wordlist, tente novamente." except Exception as e: print "Erro: "+str(e)
def saltTwo(hash, tipo): global word try: f = open(options.wl) for pwd in f.readlines(): pwd = pwd.strip() if(tipo == 0): d = hashlib.md5(pwd+options.salt).hexdigest() else: d = hashlib.sha1(pwd+options.salt).hexdigest() if(d == hash): print word+"(pass+salt)\t\t\t[+] Senha encontrada: "+pwd return print word+"(pass+salt)\t\t\t[-] Senha nao encontrada! :-(" except IOError: print "Nao foi possivel abrir sua wordlist, tente novamente." except Exception as e: print "Erro: "+str(e)
def saltOne(hash, tipo): global word try: f = open(options.wl) for pwd in f.readlines(): pwd = pwd.strip() if(tipo == 0): d = hashlib.md5(options.salt+pwd).hexdigest() else: d = hashlib.sha1(options.salt+pwd).hexdigest() if(d == hash): print word+"(salt+pass)\t\t\t[+] Senha encontrada: "+pwd return print word+"(salt+pass)\t\t\t[-] Senha nao encontrada! :-(" except IOError: print "Nao foi possivel abrir sua wordlist, tente novamente." except Exception as e: print "Erro: "+str(e) #Without Salt
def sextuple(hash, tipo): global word try: f = open(options.wl) for pwd in f.readlines(): pwd = pwd.strip() if(tipo == 0): d = hashlib.md5(hashlib.md5(hashlib.md5(hashlib.md5(hashlib.md5(hashlib.md5(pwd).hexdigest()).hexdigest()).hexdigest()).hexdigest()).hexdigest()).hexdigest() else: d = hashlib.sha1(hashlib.sha1(hashlib.sha1(hashlib.sha1(hashlib.sha1(hashlib.sha1(pwd).hexdigest()).hexdigest()).hexdigest()).hexdigest()).hexdigest()).hexdigest() if(d == hash): print "Sextuple "+ word +"\t\t\t[+] Senha encontrada: "+pwd return print "Sextuple "+ word +"\t\t\t[+] Senha nao encontrada! :-(" except IOError: print "Nao foi possivel abrir sua wordlist, tente novamente." except Exception as e: print "Erro: "+str(e)
def quintuple(hash, tipo): global word try: f = open(options.wl) for pwd in f.readlines(): pwd = pwd.strip() if(tipo == 0): d = hashlib.md5(hashlib.md5(hashlib.md5(hashlib.md5(hashlib.md5(pwd).hexdigest()).hexdigest()).hexdigest()).hexdigest()).hexdigest() else: d = hashlib.sha1(hashlib.sha1(hashlib.sha1(hashlib.sha1(hashlib.sha1(pwd).hexdigest()).hexdigest()).hexdigest()).hexdigest()).hexdigest() if(d == hash): print "Quintuple "+ word +"\t\t\t[+] Senha encontrada: "+pwd return print "Quintuple "+ word +"\t\t\t[-] Senha nao encontrada! :-(" except IOError: print "Nao foi possivel abrir sua wordlist, tente novamente." except Exception as e: print "Erro: "+str(e)
def quadruple(hash, tipo): global word try: f = open(options.wl) for pwd in f.readlines(): pwd = pwd.strip() if(tipo == 0): d = hashlib.md5(hashlib.md5(hashlib.md5(hashlib.md5(pwd).hexdigest()).hexdigest()).hexdigest()).hexdigest() else: d = hashlib.sha1(hashlib.sha1(hashlib.sha1(hashlib.sha1(pwd).hexdigest()).hexdigest()).hexdigest()).hexdigest() if(d == hash): print "Quadruple "+ word +"\t\t\t[+] Senha encontrada: "+pwd return print "Quadruple "+ word +"\t\t\t[-] Senha nao encontrada! :-(" except IOError: print "Nao foi possivel abrir sua wordlist, tente novamente." except Exception as e: print "Erro: "+str(e)
def triple(hash, tipo): global word try: f = open(options.wl) for pwd in f.readlines(): pwd = pwd.strip() if(tipo == 0): d = hashlib.md5(hashlib.md5(hashlib.md5(pwd).hexdigest()).hexdigest()).hexdigest() else: d = hashlib.sha1(hashlib.sha1(hashlib.sha1(pwd).hexdigest()).hexdigest()).hexdigest() if(d == hash): print "Triple "+ word +"\t\t\t[+] Senha encontrada: "+pwd return print "Triple "+ word +"\t\t\t[-] Senha nao encontrada! :-(" except IOError: print "Nao foi possivel abrir sua wordlist, tente novamente." except Exception as e: print "Erro: "+str(e)
def double(hash, tipo): global word try: f = open(options.wl) for pwd in f.readlines(): pwd = pwd.strip() if(tipo == 0): d = hashlib.md5(hashlib.md5(pwd).hexdigest()).hexdigest() else: d = hashlib.sha1(hashlib.sha1(pwd).hexdigest()).hexdigest() if(d == hash): print "Double "+ word +"\t\t\t[+] Senha encontrada: "+pwd return print "Double "+ word +"\t\t\t[-] Senha nao encontrada! :-(" except IOError: print "Nao foi possivel abrir sua wordlist, tente novamente." except Exception as e: print "Erro: "+str(e)
def decrypt(hash, tipo): global word try: if(tipo == 0): url = BeautifulSoup(urllib.urlopen("https://md5.gromweb.com/?md5=" + hash), "html.parser") else: url = BeautifulSoup(urllib.urlopen("https://sha1.gromweb.com/?hash=" + hash), "html.parser") password = url.find("em", {"class": "long-content string"}) password = re.sub(re.compile("<.*?>"), "", str(password)).strip() if str(password) == "None": print word+"\t\t\t\t[-] Senha nao encontrada! :-(" else: print word+"\t\t\t\t[+] Senha encontrada: " + password except IOError: decryptwl(hash, tipo)
def get_or_create_dna_sequence(rec, cur, genome_id): '''Fetch existing dna_sequence entry or create a new one''' params = {} params['seq'] = str(rec.seq) params['md5sum'] = hashlib.md5(params['seq']).hexdigest() params['accession'] = rec.annotations['accessions'][0] params['version'] = rec.annotations['sequence_version'] cur.execute("SELECT sequence_id FROM antismash.dna_sequences WHERE md5 = %s", (params['md5sum'],)) ret = cur.fetchone() if ret is None: params['genome_id'] = genome_id cur.execute("INSERT INTO antismash.dna_sequences (dna, md5, acc, version, genome_id)" "VALUES (%(seq)s, %(md5sum)s, %(accession)s, %(version)s, %(genome_id)s) RETURNING sequence_id;", params) ret = cur.fetchone() return ret[0]
def parse_cookie(cookie, securekey): logger.info (">> parse cookie : %s" % cookie) parts = cookie.split('.') part1 = parts[0] part2 = '' if len(parts) < 2 else parts[1] try: text = str(base64.b64decode(part1.encode('ascii')), encoding='utf-8') except: logger.info ("decode cookie failed") return None logger.info ("cookie content : %s" % text) thatpart2 = hashlib.md5((text+securekey).encode('ascii')).hexdigest() logger.info ("hash from part1 : %s" % thatpart2) logger.info ("hash from part2 : %s" % part2) if part2 == thatpart2: result = json.loads(text)['name'] else: result = None logger.info ("parse from cookie : %s" % result) return result
def apply(self, val): matches = self._get_matches(val) val_to_hash = str(val) if isinstance(val, int) or isinstance(val, float) else val try: # add string literal to ensure unicode hashed = hashlib.md5(val_to_hash.encode('utf-8')).hexdigest() + '' except [AttributeError, ValueError]: hashed = None if matches: blotted = '***'.join(matches.groups()) if hashed: return '{} ({})'.format(hashed, blotted) return blotted return hashed
def qiniu_upload_img(img_url): """????????? Args: img_url (string): ???? """ response = requests.get(img_url) image = response.content md5 = calc_md5(image) qiniu_url = 'http://{}/{}'.format(QINIU_HOSTNAME, md5) if requests.head(qiniu_url).ok: return qiniu_url q = Auth(QINIU_ACCESS_KEY, QINIU_SECRET_KEY) token = q.upload_token(QINIU_BUCKET, md5, 10) put_data(token, md5, image, mime_type='image/jpeg') return qiniu_url
def apop(self, user, secret): """Authorisation - only possible if server has supplied a timestamp in initial greeting. Args: user - mailbox user; secret - secret shared between client and server. NB: mailbox is locked by server from here to 'quit()' """ m = self.timestamp.match(self.welcome) if not m: raise error_proto('-ERR APOP not supported by server') import hashlib digest = hashlib.md5(m.group(1)+secret).digest() digest = ''.join(map(lambda x:'%02x'%ord(x), digest)) return self._shortcmd('APOP %s %s' % (user, digest))
def make_python_fig(self, code: str, exts: Tuple[str, ...]=('pdf', 'svg'), tight_layout=True) -> str: hashsum = hashlib.md5(code.encode('utf8')).hexdigest() prefix = hashsum[:2] path = os.path.join(self.figures_dir, prefix, hashsum) needfigure = False for ext in exts: if not os.path.isfile(os.path.join( path, self.default_figname + "." + ext)): needfigure = True break if needfigure: make_sure_path_exists(path) gl = self.pythonfigure_globals plt.close() exec(code, gl) if tight_layout: plt.tight_layout() for ext in exts: plt.savefig(os.path.join( path, self.default_figname + "." + ext)) return os.path.join(prefix, hashsum)
def reset(self, currentTime, totalTime, name, year='0'): try: if not control.setting('bookmarks') == 'true': raise Exception() timeInSeconds = str(currentTime) ok = int(currentTime) > 180 and (currentTime / totalTime) <= .92 idFile = hashlib.md5() for i in name: idFile.update(str(i)) for i in year: idFile.update(str(i)) idFile = str(idFile.hexdigest()) control.makeFile(control.dataPath) dbcon = database.connect(control.bookmarksFile) dbcur = dbcon.cursor() dbcur.execute("CREATE TABLE IF NOT EXISTS bookmark (""idFile TEXT, ""timeInSeconds TEXT, ""UNIQUE(idFile)"");") dbcur.execute("DELETE FROM bookmark WHERE idFile = '%s'" % idFile) if ok: dbcur.execute("INSERT INTO bookmark Values (?, ?)", (idFile, timeInSeconds)) dbcon.commit() except: pass
def sign(self, parameters): """ Generates the signature for autheorized API calls. Args: parameters (dict): Name and value of parameters for API call. Returns: string: Signature according to http://www.last.fm/api/webauth#6. """ sorted_params = ("{}{}".format(k, parameters[k]) for k in sorted(parameters)) md5 = hashlib.md5() string = "{}{}".format(''.join(sorted_params), self.__secret) md5.update(string.encode('utf-8')) return md5.hexdigest()
def upload_file(upload_file_name, temp): # upload_file_name????? # ??? saveas??? # ?????????,??git???saveas #key = md5(str(time.time())+''.join(random.sample(string.letters, 12))).hexdigest() # key ?????? print u"??????: ", pic_name = raw_input() uuid_6 = uuid.uuid4().get_hex()[:8] #????? key = pic_name+"_"+uuid_6+".png" copyfile(upload_file_name,join(saveas,key)) mime_type = 'image/png' token = q.upload_token(bucket, key) ret, info = put_file(token, key, upload_file_name, mime_type=mime_type, check_crc=True) print 'upload qiniu result:', info assert ret['key'] == key assert ret['hash'] == etag(upload_file_name) os.rename(upload_file_name, upload_file_name+'.old') return domain+'/'+key
def set_id(self, data): """ Set ID of document. To allow multiple files with the same path, the digest of supplied data (e.g. first 4KB) is appended to the doc ID. :param data: Data to append to docuemnt path. :type data: Anything digestable by hashlib. """ digest = hashlib.md5() digest.update(self.path.encode('utf-8')) if isinstance(data, unicode): data = data.encode('utf-8') digest.update(data) self.docid = digest.hexdigest()
def request(self, method, request_uri, headers, content, cnonce = None): """Modify the request headers""" H = lambda x: _md5(x).hexdigest() KD = lambda s, d: H("%s:%s" % (s, d)) A2 = "".join([method, ":", request_uri]) self.challenge['cnonce'] = cnonce or _cnonce() request_digest = '"%s"' % KD(H(self.A1), "%s:%s:%s:%s:%s" % ( self.challenge['nonce'], '%08x' % self.challenge['nc'], self.challenge['cnonce'], self.challenge['qop'], H(A2))) headers['authorization'] = 'Digest username="%s", realm="%s", nonce="%s", uri="%s", algorithm=%s, response=%s, qop=%s, nc=%08x, cnonce="%s"' % ( self.credentials[0], self.challenge['realm'], self.challenge['nonce'], request_uri, self.challenge['algorithm'], request_digest, self.challenge['qop'], self.challenge['nc'], self.challenge['cnonce']) if self.challenge.get('opaque'): headers['authorization'] += ', opaque="%s"' % self.challenge['opaque'] self.challenge['nc'] += 1
def buildSign(params, secretKey, host='haobtc'): if host =='haobtc' or host == 'default': sign = '' for key in sorted(params.keys()): sign += key + '=' + str(params[key]) +'&' data = sign+'secret_key='+secretKey return hashlib.md5(data.encode("utf8")).hexdigest().upper() if host == 'okcoin': sign = '' for key in sorted(params.keys()): sign += key + '=' + str(params[key]) +'&' data = sign+'secret_key='+secretKey return hashlib.md5(data.encode("utf8")).hexdigest().upper() if host == '': return if host == '': return
def _password_digest(username, password): """Get a password digest to use for authentication. """ if not isinstance(password, string_type): raise TypeError("password must be an " "instance of %s" % (string_type.__name__,)) if len(password) == 0: raise ValueError("password can't be empty") if not isinstance(username, string_type): raise TypeError("password must be an " "instance of %s" % (string_type.__name__,)) md5hash = md5() data = "%s:mongo:%s" % (username, password) md5hash.update(data.encode('utf-8')) return _unicode(md5hash.hexdigest())
def _authenticate_cram_md5(credentials, sock_info): """Authenticate using CRAM-MD5 (RFC 2195) """ source = credentials.source username = credentials.username password = credentials.password # The password used as the mac key is the # same as what we use for MONGODB-CR passwd = _password_digest(username, password) cmd = SON([('saslStart', 1), ('mechanism', 'CRAM-MD5'), ('payload', Binary(b'')), ('autoAuthorize', 1)]) response = sock_info.command(source, cmd) # MD5 as implicit default digest for digestmod is deprecated # in python 3.4 mac = hmac.HMAC(key=passwd.encode('utf-8'), digestmod=md5) mac.update(response['payload']) challenge = username.encode('utf-8') + b' ' + b(mac.hexdigest()) cmd = SON([('saslContinue', 1), ('conversationId', response['conversationId']), ('payload', Binary(challenge))]) sock_info.command(source, cmd)
def create_checksum(self): """ Creating a checksums of checksums to detect a change even if there are multiple files used to configure a service. Cleanup old checksumfiles if the config was removed. """ checksums = '' for _file in self.service_conf_files: if os.path.exists(_file): log.debug("Generating checksum for {}".format(_file)) md5 = hashlib.md5(open(_file, 'rb').read()).hexdigest() log.debug("Checksum: {}".format(md5)) checksums += md5 if checksums: return hashlib.md5(checksums).hexdigest() log.debug(("No file found to generate a checksum from. Looked for " "{}".format(self.service_conf_files))) if os.path.exists(self.checksum_file): os.remove(self.checksum_file) return None
def solution_part2(): result = 8 * [''] assigned = 0 start_int = 0 digits = {'0', '1', '2', '3', '4', '5', '6', '7'} while assigned < 8: hexhash = md5(('ugkcyxxp' + str(start_int)).encode('ascii')).hexdigest() as_str = str(hexhash) if as_str.startswith('00000') and as_str[5] in digits: idx = int(as_str[5]) if not result[idx]: result[idx] = as_str[6] assigned = len([1 for i in result if i]) print(result) start_int += 1 return ''.join(result)
def createVideoIcon(file): """ Creating a video icon/thumbnail :type file: str :param file: path to the file name :rtype: image :return: icon/thumbnail for the video """ # should install ffmpeg for the method to work successfully ffmpeg = Utils.checkFFMPEG() if ffmpeg: # generate thumbnail preview = os.path.join(mkdtemp(), hashlib.md5(file) + '.jpg') try: os.unlink(preview) except Exception: pass # capture video preview command = [ffmpeg, '-i', file, '-f', 'mjpeg', '-ss', '00:00:01', '-vframes', '1', preview, '2>&1'] exec_php(command) return file_get_contents(preview)
def ExpandBitly(self, text): if os.environ['HTTP_HOST'].find('localhost') == -1: p = re.compile('http:\/\/bit\.ly/[a-zA-Z0-9]+') m = p.findall(text) if len(m) > 0: api = bitly.Api(login='livid', apikey='R_40ab00809faf431d53cfdacc8d8b8d7f') last = None for s in m: if s != last: cache_tag = 'bitly_' + hashlib.md5(s).hexdigest() expanded = memcache.get(cache_tag) if expanded is None: expanded = api.expand(s) memcache.set(cache_tag, expanded, 2678400) last = s text = text.replace(s, expanded) return text
def gravatar(value,arg): default = "http://v2ex.appspot.com/static/img/avatar_" + str(arg) + ".png" if type(value).__name__ != 'Member': return '<img src="' + default + '" border="0" align="absmiddle" />' if arg == 'large': number_size = 73 member_avatar_url = value.avatar_large_url elif arg == 'normal': number_size = 48 member_avatar_url = value.avatar_normal_url elif arg == 'mini': number_size = 24 member_avatar_url = value.avatar_mini_url if member_avatar_url: return '<img src="'+ member_avatar_url +'" border="0" alt="' + value.username + '" />' else: gravatar_url = "http://www.gravatar.com/avatar/" + hashlib.md5(value.email.lower()).hexdigest() + "?" gravatar_url += urllib.urlencode({'s' : str(number_size), 'd' : default}) return '<img src="' + gravatar_url + '" border="0" alt="' + value.username + '" align="absmiddle" />' # avatar filter
def __init__(self, method): super(auth_chain_a, self).__init__(method) self.hashfunc = hashlib.md5 self.recv_buf = b'' self.unit_len = 2800 self.raw_trans = False self.has_sent_header = False self.has_recv_header = False self.client_id = 0 self.connection_id = 0 self.max_time_dif = 60 * 60 * 24 # time dif (second) setting self.salt = b"auth_chain_a" self.no_compatible_method = 'auth_chain_a' self.pack_id = 1 self.recv_id = 1 self.user_id = None self.user_id_num = 0 self.user_key = None self.overhead = 4 self.client_over_head = 4 self.last_client_hash = b'' self.last_server_hash = b'' self.random_client = xorshift128plus() self.random_server = xorshift128plus() self.encryptor = None
def EVP_BytesToKey(password, key_len, iv_len): # equivalent to OpenSSL's EVP_BytesToKey() with count 1 # so that we make the same key and iv as nodejs version if hasattr(password, 'encode'): password = password.encode('utf-8') cached_key = '%s-%d-%d' % (password, key_len, iv_len) r = cached_keys.get(cached_key, None) if r: return r m = [] i = 0 while len(b''.join(m)) < (key_len + iv_len): md5 = hashlib.md5() data = password if i > 0: data = m[i - 1] + password md5.update(data) m.append(md5.digest()) i += 1 ms = b''.join(m) key = ms[:key_len] iv = ms[key_len:key_len + iv_len] cached_keys[cached_key] = (key, iv) return key, iv
def post(self): # # ??????? # ????session # password = self.get_body_argument('password', '') if password: user = yield self.db.user.find_one({ 'username': self.current_user['username'] }) _ = md5(password + self.settings['salt']) if user['password'] == _.hexdigest(): if self.get_cookie('TORNADOSESSION'): self.clear_cookie('TORNADOSESSION') self.db.user.remove({ '_id': ObjectId(self.current_user['_id']) }) self.session.delete('user_session') self.redirect('/') self.custom_error('????????')
def user_action(self, *args, **kwargs): uid = self.get_body_argument('uid') user = { 'email': self.get_body_argument('email'), 'website': self.get_body_argument('website'), 'qq': self.get_body_argument('qq'), 'address': self.get_body_argument('address') } # model ?? # # password = self.get_body_argument('password', '') # password ????? if password: user['password'] = md5(password, self.settings['salt']) user = yield self.db.user.find_and_modify({ '_id': ObjectId(uid) }, { '$set': user }) self.redirect('/manage/userdetail/{}'.format(uid))
def h_file_win32(fname): try: fd = os.open(fname, os.O_BINARY | os.O_RDONLY | os.O_NOINHERIT) except OSError: raise IOError('Cannot read from %r' % fname) f = os.fdopen(fd, 'rb') m = md5() try: while fname: fname = f.read(200000) m.update(fname) finally: f.close() return m.digest() # always save these
def file_already_exists(self): """Check to see if there is a remote file with the same name and md5 sum. Returns: ``True`` if exists, ``False`` otherwise. """ if not self.remote_dir_exists: return False try: dst_hash = self._get_remote_md5() except NCError: return False src_hash = self._get_local_md5() if src_hash == dst_hash: return True return False
def _get_remote_md5(self): """Return the md5 sum of the remote file, if it exists. """ E = action_element_maker() top = E.top( E.FileSystem( E.Files( E.File( E.SrcName(self.dst), E.Operations( E.md5sum() ) ) ) ) ) nc_get_reply = self.device.action(top) reply_ele = etree.fromstring(nc_get_reply.xml) md5sum = find_in_action('md5sum', reply_ele) if md5sum is not None: return md5sum.text.strip()
def get_md5(url): #str??unicode? if isinstance(url, str): url = url.encode("utf-8") m = hashlib.md5() m.update(url) return m.hexdigest()
def md5(self): return hashlib.md5(self.stream).hexdigest();
def run(self): searchhash = '' if self.data_type == 'hash': searchhash = self.getData() if len(searchhash) != 32: self.report({'isonvs': 'unknown', 'hash': searchhash}) elif self.data_type == 'file': filepath = self.getParam('file') hasher = hashlib.md5() with io.open(filepath, mode='rb') as afile: for chunk in iter(lambda: afile.read(65536), b''): hasher.update(chunk) searchhash = hasher.hexdigest() else: self.error('Unsupported data type.') # Read files for file in self.filelist: filepath = os.path.join(self.path, file) if not os.path.isfile(filepath): continue with io.open(filepath, 'r') as afile: for line in afile: # Skipping comments if line[0] == '#': continue if searchhash.lower() in line: self.report({'isonvs': True, 'md5': searchhash}) self.report({'isonvs': False, 'md5': searchhash})
def getTempfileChecksum(self): with open(self.tempfile, 'rb') as fileHandler: checksum = hashlib.md5() while True: data = fileHandler.read(8192) if not data: break checksum.update(data) return checksum.hexdigest()
def md5(self): """ Simply return the md5 hash value associated with the content file. If the file can't be accessed, then None is returned. """ md5 = hashlib.md5() if self.open(mode=NNTPFileMode.BINARY_RO): for chunk in \ iter(lambda: self.stream.read(128*md5.block_size), b''): md5.update(chunk) return md5.hexdigest() return None