本文整理汇总了Python中md5.md5函数的典型用法代码示例。如果您正苦于以下问题:Python md5函数的具体用法?Python md5怎么用?Python md5使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了md5函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:AchillesA,项目名称:bittorrent-orig,代码行数:60,代码来源:md5crypt.py
示例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)
开发者ID:sellers,项目名称:s3tools,代码行数:26,代码来源:s3rsync.py
示例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
开发者ID:bgianfo,项目名称:last.fm-proxy,代码行数:26,代码来源:audioscrobbler.py
示例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
开发者ID:bizonix,项目名称:DropBoxLibrarySRC,代码行数:33,代码来源:pdf.py
示例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))
开发者ID:ibz,项目名称:liberatio,代码行数:31,代码来源:lastfm_bootstrap.py
示例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,
)
开发者ID:Konubinix,项目名称:Devel,代码行数:33,代码来源:konix_poorman_rsync.py
示例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)])
开发者ID:MirkoRossini,项目名称:django-redis-engine,代码行数:30,代码来源:tests.py
示例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
开发者ID:M15t,项目名称:gxdy,代码行数:27,代码来源:middleware.py
示例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()
开发者ID:kounterfeit,项目名称:text2pwn,代码行数:27,代码来源:text2pwn.py
示例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))
开发者ID:zbhknight,项目名称:payroll,代码行数:25,代码来源:views.py
示例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()
开发者ID:pillserg,项目名称:santaadventofcode,代码行数:7,代码来源:temp3.py
示例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)
开发者ID:Bystroushaak,项目名称:cherrytree2html.py,代码行数:30,代码来源:localize_pics.py
示例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)
开发者ID:xenoxaos,项目名称:Work_scripts,代码行数:26,代码来源:MBOX_uploader.py
示例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
开发者ID:nnamon,项目名称:sleekpwn,代码行数:27,代码来源:sleek.py
示例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.'
开发者ID:baifendian,项目名称:TopicTrend,代码行数:26,代码来源:create_superuser.py
示例16: user_edit_password
def user_edit_password():
form = EditPasswordForm()
if form.validate_on_submit():
username = session["name"]
op = form.originPassword.data
if not db.user.find_and_modify(
query={
"name": username,
"password": binary.Binary(md5.md5(op).digest())
},
update={
"$set": {
"password":
binary.Binary(md5.md5(form.newPassword.data).digest())
}
},
):
return u"密码错误, 就是不对"
else:
return u"修改成功, 自己刷新回去吧"
return render_template_string(
"{% from 'form_macro.html' import render_errors %}\
<form method='post' action={{ url_for('user.user_edit_password') }} >\
{{ form.hidden_tag() }} \
{{ form.originPassword.label }}\
{{ form.originPassword }} {{ render_errors(form.originPassword) }} <br>\
{{ form.newPassword.label }}\
{{ form.newPassword }} {{ render_errors(form.newPassword) }}<br>\
{{ form.rePassword.label }}\
{{ form.rePassword }} {{ render_errors(form.rePassword) }} <br>\
{{ form.submit }} \
</form>",
form=form)
开发者ID:gsk727,项目名称:renren_sdk_python,代码行数:33,代码来源:user.py
示例17: testWrite
def testWrite(self):
ftp_server_from = "stage.mozilla.org/firefox"
ftp_server_to = "stage.mozilla.org/firefox"
self.uvc.product = "Firefox"
self.uvc.platform = "Linux_x86-gcc3"
self.uvc.channel = "betatest"
self.uvc.aus_server = "https://aus4.mozilla.org"
self.uvc.to = "/firefox/4.0rc2.tar.bz2"
self.uvc.addRelease("4.0", build_id="888",
locales=("af", "de", "en-US", "ja", "zh-TW"),
patch_types=("partial", "complete"),
from_path="/firefox/4.0rc1.tar.bz2",
ftp_server_from=ftp_server_from,
ftp_server_to=ftp_server_to,
mar_channel_IDs="firefox-mozilla-beta")
self.uvc.addRelease("4.0b12", build_id="777",
locales=["af", "en-US"],
from_path="/firefox/4.0b12.tar.bz2",
ftp_server_from=ftp_server_from,
ftp_server_to=ftp_server_to)
self.uvc.addRelease("4.0b12", build_id="777",
locales=("de", "ja", "zh-TW"),
ftp_server_from=ftp_server_from,
ftp_server_to=ftp_server_to)
self.uvc.addRelease("3.7a1", build_id="666", locales=("en-US",),
ftp_server_from=ftp_server_from,
ftp_server_to=ftp_server_to)
self.uvc.write(self.tmpfile)
self.tmpfile.close()
self.assertEquals(md5(open(self.config).read()).hexdigest(),
md5(open(self.tmpfilename).read()).hexdigest())
开发者ID:Callek,项目名称:build-tools,代码行数:32,代码来源:test_release_updates_verify.py
示例18: compute_encryption_key
def compute_encryption_key(self, password = ""):
"""Algorithm 3.2. Compute the key used to decode strings
and streams. Returns None if the user password does not
pass the simple password test."""
password = (password + self.PasswordPad)[:32]
m = md5.md5()
m.update(password)
m.update(self.O)
P = struct.pack("<L", self.P)
m.update(P)
m.update(self.id1)
x = m.digest()
if self.R == 3:
for i in range(50):
x = md5.md5(x).digest()
key = x[:self.Length]
#-- if this key is right, then ecrypting the pad string will
# yield the U value.
Ucheck = RC4(key).crypt(self.PasswordPad)
if Ucheck != self.U:
# try skipping steps 3 4 and 5.
key = md5.md5(password).digest()[:5]
Ucheck = RC4(key).crypt(self.PasswordPad)
if Ucheck != self.U:
return None
return key
开发者ID:cc-archive,项目名称:jtoolkit,代码行数:28,代码来源:pdffile.py
示例19: get_auth_response
def get_auth_response(self, http_method, fullpath, username, nonce, realm, qop, cnonce, nc):
"""
Returns the server-computed digest response key.
http_method:
The request method, e.g. GET
username:
The user to be authenticated
fullpath:
The absolute URI to be accessed by the user
nonce:
A server-specified data string which should be
uniquely generated each time a 401 response is made
realm:
A string to be displayed to users so they know which
username and password to use
qop:
Indicates the "quality of protection" values supported
by the server. The value "auth" indicates authentication.
cnonce:
An opaque quoted string value provided by the client
and used by both client and server to avoid chosen
plaintext attacks, to provide mutual authentication,
and to provide some message integrity protection.
nc:
Hexadecimal request counter
"""
ha1 = self.authfunc(realm, username)
ha2 = md5.md5('%s:%s' % (http_method, fullpath)).hexdigest()
if qop:
chk = "%s:%s:%s:%s:%s:%s" % (ha1, nonce, nc, cnonce, qop, ha2)
else:
chk = "%s:%s:%s" % (ha1, nonce, ha2)
computed_response = md5.md5(chk).hexdigest()
return computed_response
开发者ID:haystack,项目名称:listit-server,代码行数:35,代码来源:authentication.py
示例20: setUp
def setUp(self):
self.cmd = Object(**{
"deviceConfig": Object(**{
"device": "localhost",
"lastmodeltime": "lastmodeltime"
}),
"command": "command",
"component": "url_" + md5("defunct").hexdigest().strip(),
"includeRegex": ".*defunct.*",
"excludeRegex": "nothing",
"replaceRegex": ".*",
"replacement": "defunct",
"primaryUrlPath": "url",
"displayName": "defunct process set",
"eventKey": "bar",
"severity": 1,
"generatedId": "url_" + md5("defunct").hexdigest().strip(),
"points": [
Object(**{
"id": "cpu_cpu",
"data": {
"id": "url_defunct",
"alertOnRestart": False,
"failSeverity": 0
}
})
]
})
self.cmd.result = Object(**{"exitCode": 0})
开发者ID:zenoss,项目名称:ZenPacks.zenoss.LinuxMonitor,代码行数:29,代码来源:testPsParser.py
注:本文中的md5.md5函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论