本文整理汇总了Python中md5.md5函数的典型用法代码示例。如果您正苦于以下问题:Python md5函数的具体用法?Python md5怎么用?Python md5使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了md5函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _md5crypt
def _md5crypt(password, the_hash):
magic, salt = the_hash[1:].split('$')[:2]
magic = '$' + magic + '$'
# /* The password first, since that is what is most unknown */ /* Then our magic string */ /* Then the raw salt */
m = md5.new()
m.update(password + magic + salt)
# /* Then just as many characters of the MD5(pw,salt,pw) */
mixin = md5.md5(password + salt + password).digest()
for i in range(0, len(password)):
m.update(mixin[i % 16])
# /* Then something really weird... */
# Also really broken, as far as I can tell. -m
i = len(password)
while i:
if i & 1:
m.update('\x00')
else:
m.update(password[0])
i >>= 1
final = m.digest()
# /* and now, just to make sure things don't run too fast */
for i in range(1000):
m2 = md5.md5()
if i & 1:
m2.update(password)
else:
m2.update(final)
if i % 3:
m2.update(salt)
if i % 7:
m2.update(password)
if i & 1:
m2.update(final)
else:
m2.update(password)
final = m2.digest()
# This is the bit that uses to64() in the original code.
itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
rearranged = ''
for a, b, c in ((0, 6, 12), (1, 7, 13), (2, 8, 14), (3, 9, 15), (4, 10, 5)):
v = ord(final[a]) << 16 | ord(final[b]) << 8 | ord(final[c])
for i in range(4):
rearranged += itoa64[v & 0x3f]; v >>= 6
v = ord(final[11])
for i in range(2):
rearranged += itoa64[v & 0x3f]; v >>= 6
return magic + salt + '$' + rearranged
示例2: _put
def _put(self, bucket, filename, key, etag=''):
headers = {}
st = os.lstat(filename)
if not stat.S_ISREG(st[stat.ST_MODE]):
print >>sys.stderr, 'skipping non-file', filename
return
if not st[stat.ST_SIZE]:
return
obj = S3.S3Object(open(filename).read(), metadata={
'mode':str(stat.S_IMODE(st[stat.ST_MODE])),
'uid':str(st[stat.ST_UID]), 'gid':str(st[stat.ST_GID]),
'atime':str(st[stat.ST_ATIME]), 'mtime':str(st[stat.ST_MTIME]),
})
etags = [ md5.md5(obj.data).hexdigest() ]
if self.opts.compress:
ext = os.path.splitext(filename)[1].lower()
if ext not in self.compressed_exts:
obj.data = self._gzip_string(obj.data)
headers['Content-Encoding'] = 'gzip'
etags.append(md5.md5(obj.data).hexdigest())
if etag not in etags:
if self.opts.verbose:
print key
r = self.conn.put(bucket, key, obj, headers=headers)
if r.http_response.status != 200:
self._perror(r)
示例3: handshake
def handshake(self, username, password, version):
self.username = username
self.password = password
timestamp = str(int(time.time()))
auth = self.hexify(md5.md5(password).digest())
auth = self.hexify(md5.md5(auth + timestamp).digest())
req = "/?hs=true&p=1.2&c=" + self.clientid + "&v=" + self.clientversion + "&u=" + username + "&t=" + timestamp + "&a=" + auth
s = httpclient.httpclient(self.handshakeurl)
s.req(req)
reslines = string.split(s.response, "\n")
if self.debug:
print "audioscrobbler: handshake " + reslines[0]
if reslines[0] != "OK":
print "audioscrobbler: Handshake error:"
print repr(s.response)
return True
self.session = reslines[1]
self.nowplayingurl = reslines[2]
self.submiturl = reslines[3]
return False
示例4: encrypt
def encrypt(self, user_pwd, owner_pwd = None, use_128bit = True):
import time, random
if owner_pwd == None:
owner_pwd = user_pwd
if use_128bit:
V = 2
rev = 3
keylen = 128 / 8
else:
V = 1
rev = 2
keylen = 40 / 8
P = -1
O = ByteStringObject(_alg33(owner_pwd, user_pwd, rev, keylen))
ID_1 = md5(repr(time.time())).digest()
ID_2 = md5(repr(random.random())).digest()
self._ID = ArrayObject((ByteStringObject(ID_1), ByteStringObject(ID_2)))
if rev == 2:
U, key = _alg34(user_pwd, O, P, ID_1)
else:
assert rev == 3
U, key = _alg35(user_pwd, rev, keylen, O, P, ID_1, False)
encrypt = DictionaryObject()
encrypt[NameObject('/Filter')] = NameObject('/Standard')
encrypt[NameObject('/V')] = NumberObject(V)
if V == 2:
encrypt[NameObject('/Length')] = NumberObject(keylen * 8)
encrypt[NameObject('/R')] = NumberObject(rev)
encrypt[NameObject('/O')] = ByteStringObject(O)
encrypt[NameObject('/U')] = ByteStringObject(U)
encrypt[NameObject('/P')] = NumberObject(P)
self._encrypt = self._addObject(encrypt)
self._encrypt_key = key
示例5: bootstrap
def bootstrap(username, password, tracks):
timestamp = str(int(time.time()))
auth = md5(md5(password).hexdigest() + timestamp).hexdigest()
authlower = md5(md5(password).hexdigest().lower() + timestamp).hexdigest().lower()
buffer = StringIO()
buffer.write("--AaB03x\r\n")
buffer.write("content-disposition: form-data; name=\"agency\"\r\n")
buffer.write("\r\n")
buffer.write("0\r\n")
buffer.write("--AaB03x\r\n")
buffer.write("content-disposition: form-data; name=\"bootstrap\"; filename=\"iTunes_bootstrap.xml.gz\"\r\n")
buffer.write("Content-Transfer-Encoding: binary\r\n")
buffer.write("\r\n")
zip = gzip.GzipFile("iTunes_bootstrap.xml", "w", 6, buffer)
zip.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n")
zip.write("<bootstrap version=\"1.0\" product=\"iTunes\">\n")
for track in tracks:
zip.write(track_template % track)
zip.write("</bootstrap>\n")
zip.close()
buffer.write("\r\n")
buffer.write("--AaB03x--")
buffer.seek(0)
url_template = "http://bootstrap.last.fm/bootstrap/index.php?user=%(username)s&time=%(timestamp)s&auth=%(auth)s&authlower=%(authlower)s"
url = url_template % {'username': username, 'timestamp': timestamp, 'auth': auth, 'authlower': authlower}
headers = {"Content-type": "multipart/form-data, boundary=AaB03x", "Cache-Control": "no-cache", "Accept": "*/*"}
urllib2.urlopen(urllib2.Request(url, buffer.read(), headers))
示例6: main
def main():
args = parser.parse_args()
logging.basicConfig(level=LEVELS[args.verbosity])
srcs = set(get_files(args.source, excludes=args.excludes))
dsts = set(get_files(args.dest, excludes=args.excludes))
for extra in dsts - srcs:
dst = os.path.join(args.dest, extra)
logger.info("del {}".format(dst))
os.unlink(dst)
for common in srcs & dsts:
src = os.path.join(args.source, common)
dst = os.path.join(args.dest, common)
src_sig = md5.md5(open(src, "rb").read()).hexdigest()
dst_sig = md5.md5(open(dst, "rb").read()).hexdigest()
if src_sig != dst_sig:
logger.info("{} X-> {}".format(src, dst))
logger.debug("{} vs {}".format(src_sig, dst_sig))
os.unlink(dst)
shutil.copy2(
src,
dst,
)
for tocreate in srcs - dsts:
src = os.path.join(args.source, tocreate)
dst = os.path.join(args.dest, tocreate)
logger.info("{} -> {}".format(src, dst))
directory = os.path.dirname(dst)
if not os.path.exists(directory):
os.makedirs(directory)
shutil.copy2(
src,
dst,
)
示例7: atest_insert_transaction
def atest_insert_transaction(self):
"""
stress test, used to find out how much network latency
affects performance using transactions.
"""
n = 100
ng = 100
ngc = 100
l = []
#print redis_transaction.commit_manually(using = 'native')
#print transaction.commit_manually()
with redis_transaction.commit_manually(using = 'native'):
print "begin"
for i in range(n):
tit = md5(str(random.random())+str(i)).hexdigest()
l.append(tit)
Post.objects.create(
title = tit,
text = " ".join(
[md5(
str(random.random())+\
str(t)+\
str(i)).hexdigest() for t in range(20)]
)
)
redis_transaction.commit()
for i in range(ng):
p = Post.objects.get(title = l[random.randint(0,n-1)] )
for i in range(ngc):
Post.objects.filter(title__contains = l[random.randint(0,n-1)])
示例8: process_response
def process_response(self, request, response):
if response['Content-Type'].startswith('text/html') and settings.CACHE_BACKEND not in ['', None, 'dummy:///']:
soup = BeautifulSoup(response.content)
head = soup.head
#[script.extract() for script in head.findAll(lambda x: x.name == 'script' and 'src' in dict(x.attrs) and x['src'].startswith(settings.MEDIA_URL) )]
#[css.extract() for css in head.findAll(lambda x: x.name == 'link' and 'href' in dict(x.attrs) and x['href'].startswith(settings.MEDIA_URL) )]
scripts = head.findAll(lambda x: x.name == 'script' and 'src' in dict(x.attrs) and x['src'].startswith(settings.MEDIA_URL) )
css = head.findAll(lambda x: x.name == 'link' and 'href' in dict(x.attrs) and x['href'].startswith(settings.MEDIA_URL) )
script_sources = [x['src'] for x in scripts]
new_script = md5(boundary.join(script_sources)).hexdigest()
cache.set(new_script, script_sources)
[x.extract() for x in scripts]
css_sources = [x['href'] for x in css]
new_css = md5(boundary.join(css_sources)).hexdigest()
cache.set(new_css, css_sources)
[x.extract() for x in css]
tag = Tag(soup, "script", [("type", "text/javascript"), ("src", reverse('cached_asset', kwargs={'asset':new_script+".js"}) )])
head.insert(0, tag)
tag = Tag(soup, "link", [("type", "text/css"), ("href", reverse('cached_asset', kwargs={'asset':new_css+".css"})), ('rel', 'stylesheet')])
head.insert(0, tag)
response.content = soup.prettify()
return response
示例9: main
def main():
print " "
resp = raw_input("Choose your encode: ")
print " "
if resp == "md5":
for _ in range(100):
print " "
md5()
elif resp == "base64":
for _ in range(100):
print " "
base()
elif resp == "hex":
for _ in range(100):
print " "
hexa()
elif resp == "url":
pr = "----URL+ENCODER----"
print pr.center(80, ' ')
for _ in range(100):
print " "
urlenc()
elif resp == "top":
main()
else:
print "Bad input."
sys.exit()
示例10: login
def login(request, error=''):
if checkLogin(request):
return HttpResponseRedirect("/wm/index")
elif request.method == "POST":
lF = loginForm(request.POST)
if lF.is_valid():
data = lF.cleaned_data
try:
u = User.objects.get(stuNum=data['stuNum'], erase=0)
except User.DoesNotExist:
errorList = "用户名错误"
lF = loginForm()
return render_to_response("wm/login.html", {"form": lF,"error":errorList,}, context_instance=RequestContext(request))
if u.password == md5(md5(data['password']).hexdigest()+u.salt).hexdigest():
request.session['user'] = u
request.session.set_expiry(0)
return HttpResponseRedirect("/wm/index/")
else:
errorList = "密码错误"
return render_to_response("wm/login.html", {"form": lF,"error":errorList,}, context_instance=RequestContext(request))
else:
return HttpResponseRedirect("/wm/login")
else:
lF = loginForm()
return render_to_response("wm/login.html", {"form": lF,"error":error,}, context_instance=RequestContext(request))
示例11: mine_presents
def mine_presents(key):
hash = md5(key + str(0))
count = 0
while not hash.hexdigest()[:6] == '000000':
count += 1
hash = md5(key + str(count))
return count, hash.hexdigest()
示例12: localize_image
def localize_image(path, out_dir):
new_path = out_dir + "/" + os.path.basename(path)
if path.startswith("http://") or path.startswith("https://"):
local_name = "/tmp/pic_" + os.path.basename(path).replace("/", "")
with open(local_name, "wb") as f:
f.write(Downloader().download(path))
path = local_name
if not os.path.exists(path):
return path
if os.path.exists(new_path):
path_md5 = md5(open(path).read()).hexdigest()
new_path_md5 = md5(open(new_path).read()).hexdigest()
if path_md5 != new_path_md5:
while os.path.exists(new_path):
suffix = new_path.rsplit(".", 1)[1]
new_path = md5(os.path.basename(new_path)).hexdigest()
new_path = out_dir + "/" + new_path + "." + suffix
if not os.path.exists(new_path):
if path.startswith("http://") or path.startswith("https://"):
with open(new_path, "wb") as f:
f.write(Downloader().download(path))
else:
shutil.copy(path, new_path)
return "./" + os.path.basename(new_path)
示例13: upload
def upload(imap, src, err, time_fields, f, message_digests, mbox_hash):
print >> sys.stderr, "Counting the mailbox (it could take a while for the large one)."
p = Progress(len(src))
for i, msg in src.iteritems():
try:
msg_hash = md5.md5(msg.as_string()).hexdigest()
print md5.md5(msg.as_string()).hexdigest()
p.begin(msg, f)
# check if the hash combo already exists, if it is, don't reupload
if mbox_hash + msg_hash in message_digests:
print >> f, "message already uploaded"
p.endNg("Already Uploaded", f)
continue
r, r2 = imap.upload(msg.get_delivery_time(time_fields), msg.as_string(), 3)
if r != "OK":
raise Exception(r2[0]) # FIXME: Should use custom class
p.endOk(f)
message_digests.add(mbox_hash + msg_hash)
continue
except socket.error, e:
p.endNg("Socket error: " + str(e), f)
except Exception, e:
p.endNg(e, f)
示例14: check_flags
def check_flags(host):
# Check the public flags
results = {}
# Check the web flag
try:
lighttpd_flag = requests.get("http://%s" % host, timeout=2).text
web_hash = md5.md5(lighttpd_flag).hexdigest()
results['web'] = web_hash == "fa477c36d6c52d52bbd9b6af7df708fa"
except:
results['web'] = False
# Check the ftp flag
try:
ftp_conn = FTP(host, user="public", passwd="password", timeout=2)
ss = StringIO.StringIO()
ftp_conn.retrbinary("RETR file", ss.write)
ftp_hash = md5.md5(ss.getvalue()).hexdigest()
ss.close()
results['ftp'] = ftp_hash == "4d91498a12508cd7f51fe6d5265ee521"
except:
results['ftp'] = False
log.info("Flags for %s: web is %s | ftp is %s." % (host,
"unmodified" if results['web'] else "modified",
"unmodified" if results['ftp'] else "modified"))
return results
示例15: handle
def handle(self, *args, **options):
while True:
username = raw_input('请输入用户名(至少5位字符):')
if len(username.decode('utf8')) > 4:
break
else:
self.stdout.write(u'============输入的用户名无效,请重新输入============')
while True:
pwd = getpass.getpass('请输入密码(至少5位字符):')
if len(pwd.decode('utf8')) > 4:
break
else:
self.stdout.write(u'============输入的密码无效,请重新输入============')
import md5
from django.contrib.auth.models import User
md5_pwd = md5.md5(md5.md5(pwd).hexdigest()).hexdigest()
try:
User.objects.create_superuser(username, None, md5_pwd)
self.stdout.write(u'============管理员%s创建成功============'%username)
except:
self.stdout.write(u'============用户名已存在============')
print 'exit.'