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,
}
python类md5()的实例源码
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())