本文整理汇总了Python中md5.new函数的典型用法代码示例。如果您正苦于以下问题:Python new函数的具体用法?Python new怎么用?Python new使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了new函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: auth_flickr
def auth_flickr(request):
from agro.sources import utils
api, secret, url = 'e22dd4a81125531e047036ed1ab2a9e7', '72a484d250375bdf', ''
token = ''
user_name, user_id = '', ''
frob = request.GET.get('frob', '')
if frob:
api_sig = md5.new('%sapi_key%sfrob%smethodflickr.auth.getToken' % (secret, api, frob)).hexdigest()
params = urllib.urlencode({'api_key':api, 'frob':frob, 'method':'flickr.auth.getToken', 'api_sig':api_sig})
res = utils.get_remote_data("http://api.flickr.com/services/rest/?" + params)
if res.get("stat", "") == "fail":
log.error("flickr retrieve failed.")
log.error("%s" % res.get("stat"))
return False
#token = res.get('auth')
auth_res = res.getchildren()[0]
token = auth_res.find('token').text
user = auth_res.find('user')
user_name = user.get('username')
user_id = user.get('nsid')
else:
if request.method == 'POST':
perms = 'read'
api_sig = md5.new('%sapi_key%sperms%s' % (secret, api, perms)).hexdigest()
params = urllib.urlencode({'api_key':api, 'perms':perms, 'api_sig':api_sig})
return HttpResponseRedirect('http://flickr.com/services/auth/?%s' % params)
else:
pass
return render_to_response('flickr_auth.html', {'api':api, 'secret':secret, 'user_name':user_name, 'user_id':user_id, 'token':token,}, context_instance=RequestContext(request))
示例2: _unzipIterChunkyTest
def _unzipIterChunkyTest(self, compression, chunksize, lower, upper):
"""
unzipIterChunky should unzip the given number of bytes per iteration.
"""
junk = ' '.join([str(random.random()) for n in xrange(1000)])
junkmd5 = md5.new(junk).hexdigest()
tempdir = filepath.FilePath(self.mktemp())
tempdir.makedirs()
zfpath = tempdir.child('bigfile.zip').path
self._makebigfile(zfpath, compression, junk)
uziter = zipstream.unzipIterChunky(zfpath, tempdir.path,
chunksize=chunksize)
r = uziter.next()
# test that the number of chunks is in the right ballpark;
# this could theoretically be any number but statistically it
# should always be in this range
approx = lower < r < upper
self.failUnless(approx)
for r in uziter:
pass
self.assertEqual(r, 0)
newmd5 = md5.new(
tempdir.child("zipstreamjunk").open().read()).hexdigest()
self.assertEqual(newmd5, junkmd5)
示例3: update_feeds
def update_feeds():
context = Context.objects.get(pk=1)
feeds = Feed.objects.filter(enabled=True)
for f in feeds:
try:
print "Starting %s..." % (f.title)
stream = feedparser.parse(f.url)
for e in stream['entries']:
try:
print "Getting entry id %s" % (e.id)
if Item.objects.filter(md5sum=md5.new(e.link).hexdigest()).count() > 0:
print 'Skipping duplicate item'
else:
e_date = e.updated_parsed
if not e_date:
e_date = datetime.datetime.utcnow()
if hasattr(e, "summary"):
e_content = e.summary.encode('ascii', 'xmlcharrefreplace')
elif hasattr(e, "content"):
e_content = e.content[0].value.encode('ascii', 'xmlcharrefreplace')
i = Item(feed = f,
md5sum = md5.new(e.link).hexdigest(),
guid = e.id,
title = e.title.encode('ascii', 'xmlcharrefreplace'),
link = e.link,
date = datetime.datetime.utcfromtimestamp(calendar.timegm(e_date)),
content = e_content,
context = context,
)
i.save()
print "%s - %s - Added!" % (f.title, i.title)
except Exception, e:
print e
except Exception, e:
print e
示例4: find_hotels
def find_hotels(city, country, state):
service = "http://api.ean.com/ean-services/rs/hotel/"
version = "v3/"
method = "list"
other_elements = "&cid=YOUR ACCOUNT NUMBER HERE&customerIpAddress=50.148.140.1&customerUserAgent=OSX10.9.5&customerSessionId=123456&minorRev=30&locale=en_US¤cyCode=USD"
response_type = "json"
API_KEY = "YOUR API KEY HERE"
API_secret= "YOUR API SECRET HERE"
hash = md5.new()
timestamp = str(int(time.time()))
signature = md5.new(API_KEY + API_secret + timestamp).hexdigest()
city = "%s" % (city)
countryCode = "%s" % (country)
state = "%s" % (state)
print '\n------------------------------\nCheck out this list of hotel suggestions\n------------------------------'
hotel_url = service + version + method + '?apiKey=' + API_KEY + '&sig=' + signature + '&_type=' + response_type + other_elements + '&city=' + city + '&countryCode=' + countryCode + '&stateProvinceCode=' + state
response = urlopen(hotel_url)
json_response = load(response)
firstSix = json_response['HotelListResponse']['HotelList']['HotelSummary'][0:6]
for hotels in firstSix:
print "\nHotel Name: ", hotels["name"]
print "Address: ", hotels["address1"]
print "Rating: ", hotels["hotelRating"]
print "Location: ", hotels["locationDescription"]
exit()
示例5: PwCrypt
def PwCrypt(self, password):
"""Obfuscate password
RADIUS hides passwords in packets by using an algorithm
based on the MD5 hash of the pacaket authenticator and RADIUS
secret. If no authenticator has been set before calling PwCrypt
one is created automatically. Changing the authenticator after
setting a password that has been encrypted using this function
will not work.
@param password: plaintext password
@type password: string
@return: obfuscated version of the password
@rtype: string
"""
if self.authenticator == None:
self.authenticator = self.CreateAuthenticator()
buf = password
if len(password) % 16 != 0:
buf += "\x00" * (16 - (len(password) % 16))
hash = md5.new(self.secret + self.authenticator).digest()
result = ""
last = self.authenticator
while buf:
hash = md5.new(self.secret + last).digest()
for i in range(16):
result += chr(ord(hash[i]) ^ ord(buf[i]))
last = result[-16:]
buf = buf[16:]
return result
示例6: continuity
def continuity(url):
import md5
format = '%25s: %s'
# first fetch the file with the normal http handler
opener = urllib2.build_opener()
urllib2.install_opener(opener)
fo = urllib2.urlopen(url)
foo = fo.read()
fo.close()
m = md5.new(foo)
print format % ('normal urllib', m.hexdigest())
# now install the keepalive handler and try again
opener = urllib2.build_opener(HTTPHandler())
urllib2.install_opener(opener)
fo = urllib2.urlopen(url)
foo = fo.read()
fo.close()
m = md5.new(foo)
print format % ('keepalive read', m.hexdigest())
fo = urllib2.urlopen(url)
foo = ''
while 1:
f = fo.readline()
if f: foo = foo + f
else: break
fo.close()
m = md5.new(foo)
print format % ('keepalive readline', m.hexdigest())
示例7: api
def api(self, site, method_name, GET={}, POST={}):
if site == 'vk.com':
GET['access_token'] = self.app_data[site]['access_token']
GET = urllib.urlencode(GET)
POST = urllib.urlencode(POST)
url = oauth_data[site]['url_api']
query = oauth_data[site]['query'] + method_name +'?'+ urllib.urlencode(self.settings_api) +'&'+ GET
if POST != '': _POST = '&'+POST
else: _POST = ''
if acceessPermission[site]['nohttps']:
sig = '&sig='+md5.new(query+_POST+self.app_data[site]['secret']).hexdigest()
else: sig = ''
res = self.openers[site].open(url+query+sig, POST)
elif site == 'ok.ru':
GET['application_key'] = self.user_data[site][3]
GET['method'] = method_name
keys = GET.keys()
keys.sort()
sig = ''
for key in keys:
sig += key +'='+ str(GET[key])
sig = md5.new(sig+self.app_data[site]['session_secret_key']).hexdigest().lower()
GET['access_token'] = self.app_data[site]['access_token']
GET['sig'] = sig
if self.app_data[site].has_key('api_server'): url = self.app_data[site]['api_server']
else: url = oauth_data[site]['url_api']
res = self.openers[site].open(url + oauth_data[site]['query'] + urllib.urlencode(GET))
elif site == 'disk.yandex.ru': pass
return self._process_response(res, site)
示例8: post
def post(self):
ip = self.request.get('ip')
service = 'http://api.quova.com/'
version = 'v1/'
method = 'ipinfo/'
apikey = '100.tkdykh8mvt7uut8ychhv'
secret = 'Pd3c9pzT'
hash = md5.new()
timestamp = str(int(time.time()))
sig = md5.new(apikey + secret + timestamp).hexdigest()
url = service + version + method + ip + '?apikey=' + apikey + '&sig=' + sig + '&format=xml'
xml = urllib2.urlopen(url).read()
doc = parseString(xml)
ip_address = doc.getElementsByTagName('ip_address')[0].firstChild.nodeValue
organization = doc.getElementsByTagName('organization')[0].firstChild.nodeValue
carrier = doc.getElementsByTagName('carrier')[0].firstChild.nodeValue
sld = doc.getElementsByTagName('sld')[0].firstChild.nodeValue
country = doc.getElementsByTagName('country')[0].firstChild.nodeValue
state = doc.getElementsByTagName('state')[0].firstChild.nodeValue
city = doc.getElementsByTagName('city')[0].firstChild.nodeValue
postal_code = doc.getElementsByTagName('postal_code')[0].firstChild.nodeValue
lat = doc.getElementsByTagName('latitude')[0].firstChild.nodeValue
lon = doc.getElementsByTagName('longitude')[0].firstChild.nodeValue
g = PyMap()
g.key = "ABQIAAAAGcWIjwYvD9qHwmbKuSQEsxQ_LYszwfeN3sChNNHex23LZKwkgRTB3_7Qo5_EhYBGijp8h1khiBFjkg"
g.maps[0].zoom = 12
s = [lat,lon, ip_address+'<br>'+organization+'<br>'+carrier+'<br>'+sld+'<br>'+country+'<br>'+state+'<br>'+city+'<br>'+postal_code+'<br>'+lat+'<br>'+lon]
g.maps[0].setpoint(s)
g.maps[0].center = (lat,lon)
self.response.out.write(g.showhtml())
示例9: _pkt_R
def _pkt_R(self):
#
# Startup Response
#
code = _unpack('!i', self.__read_bytes(4))[0]
if code == 0:
self.__authenticated = 1
#print 'Authenticated!'
elif code == 1:
raise InterfaceError('Kerberos V4 authentication is required by server, but not supported by this client')
elif code == 2:
raise InterfaceError('Kerberos V5 authentication is required by server, but not supported by this client')
elif code == 3:
self.__send(_pack('!i', len(self.__passwd)+5) + self.__passwd + '\0')
elif code == 4:
salt = self.__read_bytes(2)
try:
import crypt
except:
raise InterfaceError('Encrypted authentication is required by server, but Python crypt module not available')
cpwd = crypt.crypt(self.__passwd, salt)
self.__send(_pack('!i', len(cpwd)+5) + cpwd + '\0')
elif code == 5:
import md5
m = md5.new(self.__passwd + self.__userid).hexdigest()
m = md5.new(m + self.__read_bytes(4)).hexdigest()
m = 'md5' + m + '\0'
self.__send(_pack('!i', len(m)+4) + m)
else:
raise InterfaceError('Unknown startup response code: R%d (unknown password encryption?)' % code)
示例10: mkpasswd
def mkpasswd(pwd,hash='ssha'):
"""Generate hashed passwords. Originated from mkpasswd in Luma
"""
alg = {
'ssha':'Seeded SHA-1',
'sha':'Secure Hash Algorithm',
'smd5':'Seeded MD5',
'md5':'MD5',
'crypt':'Standard unix crypt'
}
# Don't add support for sambapasswords unless we're using it
if (update_sambapassword):
alg['lmhash'] = 'Lanman hash'
alg['nthash'] = 'NT Hash'
if hash not in alg.keys():
return "Algorithm <%s> not supported in this version." % hash
else:
salt = getsalt()
if hash == "ssha":
return "{SSHA}" + base64.encodestring(sha.new(str(pwd) + salt).digest() + salt)
elif hash == "sha":
return "{SHA}" + base64.encodestring(sha.new(str(pwd)).digest())
elif hash == "md5":
return "{SHA}" + base64.encodestring(md5.new(str(pwd)).digest())
elif hash == "smd5":
return "{SMD%}" + base64.encodestring(md5.new(str(pwd) + salt).digest() + salt)
elif hash == "crypt":
return "{CRYPT}" + crypt.crypt(str(pwd),getsalt(length=2))
# nt/lm-hash are used directly in their own password-attributes.. no need to prefix the hash
elif hash == "lmhash":
return smbpasswd.lmhash(pwd)
elif hash == "nthash":
return smbpasswd.nthash(pwd)
示例11: __init__
def __init__(self, *args, **kwargs):
super(UserFile, self).__init__(*args, **kwargs)
self.errors = []
self.errors_es = []
obj_list = {}
for line in self.xml_text.split('\n'):
num = self.xml_text.split('\n').index(line) + 1
if ('<map' in line):
obj = MapElement(line, num)
md5_obj = md5.new()
md5_obj.update(obj.element_name)
obj_hash = md5_obj.hexdigest()
if obj_hash in obj_list.keys():
pass
obj_list[obj_hash] = obj
for item in obj.err_list:
self.errors.append(item)
for item in obj.err_list_es:
self.errors_es.append(item)
else:
obj = XMLElement(line, num)
md5_obj = md5.new()
md5_obj.update(obj.element_name)
obj_hash = md5_obj.hexdigest()
obj_list[obj_hash] = obj
for item in obj.err_list:
self.errors.append(item)
for item in obj.err_list_es:
self.errors_es.append(item)
示例12: test_eventteams_update
def test_eventteams_update(self):
self.teams_auth.put()
team_list = ['frc254', 'frc971', 'frc604']
request_body = json.dumps(team_list)
request_path = '/api/trusted/v1/event/2014casj/team_list/update'
sig = md5.new('{}{}{}'.format('321tEsTsEcReT', request_path, request_body)).hexdigest()
response = self.testapp.post(request_path, request_body, headers={'X-TBA-Auth-Id': 'tEsT_id_0', 'X-TBA-Auth-Sig': sig}, expect_errors=True)
self.assertEqual(response.status_code, 200)
db_eventteams = EventTeam.query(EventTeam.event == self.event.key).fetch(None)
self.assertEqual(len(db_eventteams), 3)
self.assertTrue('2014casj_frc254' in [et.key.id() for et in db_eventteams])
self.assertTrue('2014casj_frc971' in [et.key.id() for et in db_eventteams])
self.assertTrue('2014casj_frc604' in [et.key.id() for et in db_eventteams])
team_list = ['frc254', 'frc100']
request_body = json.dumps(team_list)
sig = md5.new('{}{}{}'.format('321tEsTsEcReT', request_path, request_body)).hexdigest()
response = self.testapp.post(request_path, request_body, headers={'X-TBA-Auth-Id': 'tEsT_id_0', 'X-TBA-Auth-Sig': sig}, expect_errors=True)
self.assertEqual(response.status_code, 200)
db_eventteams = EventTeam.query(EventTeam.event == self.event.key).fetch(None)
self.assertEqual(len(db_eventteams), 2)
self.assertTrue('2014casj_frc254' in [et.key.id() for et in db_eventteams])
self.assertTrue('2014casj_frc100' in [et.key.id() for et in db_eventteams])
示例13: test_awards_update
def test_awards_update(self):
self.awards_auth.put()
awards = [{'name_str': 'Winner', 'team_key': 'frc254'},
{'name_str': 'Winner', 'team_key': 'frc604'},
{'name_str': 'Volunteer Blahblah', 'team_key': 'frc1', 'awardee': 'Bob Bobby'}]
request_body = json.dumps(awards)
request_path = '/api/trusted/v1/event/2014casj/awards/update'
sig = md5.new('{}{}{}'.format('321tEsTsEcReT', request_path, request_body)).hexdigest()
response = self.testapp.post(request_path, request_body, headers={'X-TBA-Auth-Id': 'tEsT_id_4', 'X-TBA-Auth-Sig': sig}, expect_errors=True)
self.assertEqual(response.status_code, 200)
db_awards = Award.query(Award.event == self.event.key).fetch(None)
self.assertEqual(len(db_awards), 2)
self.assertTrue('2014casj_1' in [a.key.id() for a in db_awards])
self.assertTrue('2014casj_5' in [a.key.id() for a in db_awards])
awards = [{'name_str': 'Winner', 'team_key': 'frc254'},
{'name_str': 'Winner', 'team_key': 'frc604'}]
request_body = json.dumps(awards)
sig = md5.new('{}{}{}'.format('321tEsTsEcReT', request_path, request_body)).hexdigest()
response = self.testapp.post(request_path, request_body, headers={'X-TBA-Auth-Id': 'tEsT_id_4', 'X-TBA-Auth-Sig': sig}, expect_errors=True)
self.assertEqual(response.status_code, 200)
db_awards = Award.query(Award.event == self.event.key).fetch(None)
self.assertEqual(len(db_awards), 1)
self.assertTrue('2014casj_1' in [a.key.id() for a in db_awards])
示例14: info
def info(model, msg):
print '**** %s ****' % msg
print 'md5(Wv) = ', md5.new(model.Wv.get_value()).hexdigest()
print 'rstate = ', model.theano_rng.rstate
print 'state_updates:'
for s in model.theano_rng.state_updates:
print '\t', md5.new(s[0].get_value()).hexdigest()
示例15: change_password
def change_password(request, data, user):
'''
API to change password
:param request:
:param data:
:param user:
'''
try:
user_id = user.id
old_password = data['old_password'].strip()
new_password = data['new_password'].strip()
if md5.new(old_password).hexdigest() != user.password:
return custom_error(
"The current password you have entered is incorrect.")
user.password = md5.new(new_password).hexdigest()
user.password_reset = False
user.save()
log.info("user : " + user.email + " : changed password")
return json_response({"status": 1,
"message": "Password changed successfully."})
except Exception as error:
log.error("Change password failed : " + error.message)
return custom_error("Failed to change the password.")