• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python sha.sha函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中sha.sha函数的典型用法代码示例。如果您正苦于以下问题:Python sha函数的具体用法?Python sha怎么用?Python sha使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了sha函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: agreement_scale

    def agreement_scale(self, nicklist, msg):
        question = msg.split("question:")[-1].strip()

        phrase = "The question is \"%s\". " % question
        phrase = "People that agree completely will go to that end of the room "
        phrase += "(100%), people that disagree on the other (0%). "
        self.msg(self.factory.channel, phrase)

        phrase = ""
        agreements = {}
        for nick in nicklist:
            import sha
            digest = sha.sha(question.lower()).digest() + sha.sha(nick).digest()
            digest = sha.sha(digest).digest()
            val = (ord(digest[-1]) + ord(digest[-2])) % 100

            if val not in agreements.keys():
                agreements[val] = []
            agreements[val].append(nick)

        for percent, nicks in agreements.items():
            # Sort them in the right order
            for nick in nicks:
                phrase += "%s %s%%, " % (nick, percent)

        self.msg(self.factory.channel, phrase)
开发者ID:vmon,项目名称:gunnerbot,代码行数:26,代码来源:gunnerbot.py


示例2: computePackageVerification

def computePackageVerification(g, dirname, excluded):
    # SPDX 1.2 Section 4.7
    # The SPDXTools command "GenerateVerificationCode" can be used to
    # check the verification codes created.  Note that you must manually
    # remove "license.spdx" from the unpacked dist directory before
    # computing the verification code.

    verify_node = BNode()

    hashes = []
    for dirpath, dirnames, filenames in os.walk(dirname):
        for fn in filenames:
            full_fn = os.path.join(dirpath, fn)
            f = open(full_fn, 'rb')
            d = f.read()
            f.close()

            if full_fn in excluded:
                #print('excluded in verification: ' + full_fn)
                continue
            #print('included in verification: ' + full_fn)

            file_sha1 = sha.sha(d).digest().encode('hex').lower()
            hashes.append(file_sha1)

    #print(repr(hashes))
    hashes.sort()
    #print(repr(hashes))
    verify_code = sha.sha(''.join(hashes)).digest().encode('hex').lower()

    for fn in excluded:
        g.add((verify_node, SPDX.packageVerificationCodeExcludedFile, Literal(fn)))
    g.add((verify_node, SPDX.packageVerificationCodeValue, Literal(verify_code)))

    return verify_node
开发者ID:harold-b,项目名称:duktape,代码行数:35,代码来源:create_spdx_license.py


示例3: next_block

    def next_block(self):
	if self.level == 0:
           data = self.f.read(BY2BLK)
           if len(data) == 0:
               self.level += 1
           else:
               self.hashes.append(sha.sha(data))
	       sd = sha.sha(data).digest()
	       return data
        if self.level > 0: 
	   hashdata = ""
	   hnum = 0
	   while len(self.hashes) > 0 and hnum < H2BLK:
	       hashdata += self.hashes[0].digest()
	       self.hashes.remove(self.hashes[0])
               hnum += 1
	   self.nexthash.append(sha.sha(hashdata))        
	   if len(self.hashes) == 0 and len(self.nexthash) == 1:
	       self.rootkey = self.nexthash[0].digest()
               self.eoflag = True
           elif len(self.hashes) == 0:
               self.hashes = self.nexthash
	       self.nexthash = []
	       self.level += 1
	   return hashdata
开发者ID:Amit-DU,项目名称:dht,代码行数:25,代码来源:filestore.py


示例4: makeX

def makeX(salt, username, password):
    if len(username)>=256:
        raise ValueError("username too long")
    if len(salt)>=256:
        raise ValueError("salt too long")
    return stringToNumber(sha.sha(salt + sha.sha(username + ":" + password)\
           .digest()).digest())
开发者ID:Eforcers,项目名称:inbox-cleaner,代码行数:7,代码来源:mathtls.py


示例5: agreement

 def agreement(question, nick):
     import sha
     digest = sha.sha(question.lower()).digest() + sha.sha(nick).digest()
     digest = sha.sha(digest).hexdigest()
     seed = int(digest[-8:], 16)
     r = random.Random(seed)
     return r.uniform(0, 100)
开发者ID:hellais,项目名称:gunnerbot,代码行数:7,代码来源:gunnerbot.py


示例6: create_wsse_auth

def create_wsse_auth(username, password):
  created = datetime.now().isoformat() + "Z"
  nonce   = b64encode(sha.sha(str(time() + random())).digest())
  digest  = b64encode(sha.sha(nonce + created + password).digest())
  wsse  = 'UsernameToken Username="%(u)s", PasswordDigest="%(p)s", Nonce="%(n)s", Created="%(c)s"'
  value = dict(u = username, p = digest, n = nonce, c = created)
  return wsse % value
开发者ID:nayutaya,项目名称:ironnews-sandbox,代码行数:7,代码来源:post1.py


示例7: createWSSEToken

 def createWSSEToken(self):
   nonce = sha.sha(str(time.time() + random.random())).digest()
   nonce_enc = base64.encodestring(nonce).strip()
   created = datetime.datetime.now().isoformat() + 'Z'
   password_digest = sha.sha(nonce + created + self.password).digest()
   password_digest_enc = base64.encodestring(password_digest).strip()
   self.wsse_token = 'UsernameToken Username="%s", PasswordDigest="%s", Nonce="%s", Created="%s"' % (self.username, password_digest_enc, nonce_enc, created)
开发者ID:ogawa,项目名称:hatena-bookmarker-appengine,代码行数:7,代码来源:hatena_api.py


示例8: got_metadata

    def got_metadata(self, permid, message, selversion):    
        """ receive torrent file from others """
        
        # Arno, 2007-06-20: Disabled the following code. What's this? Somebody sends 
        # us something and we refuse? Also doesn't take into account download help 
        #and remote-query extension.
        
        #if self.upload_rate <= 0:    # if no upload, no download, that's the game
        #    return True    # don't close connection
        
        try:
            message = bdecode(message[1:])
        except:
            print_exc()
            return False
        if not isinstance(message, dict):
            return False
        try:
            infohash = message['torrent_hash']
            if not isValidInfohash(infohash):
                return False

            if not infohash in self.requested_torrents:    # got a torrent which was not requested
                return True
            if self.torrent_db.hasMetaData(infohash):
                return True
            
            metadata = message['metadata']
            if not self.valid_metadata(infohash, metadata):
                return False
            if DEBUG:
                torrent_size = len(metadata)
                print >> sys.stderr,"metadata: Recvd torrent", `infohash`, sha(infohash).hexdigest(), torrent_size
            
            extra_info = {}
            if selversion >= OLPROTO_VER_FOURTH:
                try:
                    extra_info = {'leecher': message.get('leecher', -1),
                              'seeder': message.get('seeder', -1),
                              'last_check_time': message.get('last_check_time', -1),
                              'status':message.get('status', 'unknown')}
                except Exception, msg:
                    print_exc()
                    print >> sys.stderr, "metadata: wrong extra info in msg - ", message
                    extra_info = {}
                
            filename = self.save_torrent(infohash, metadata, extra_info=extra_info)
            self.requested_torrents.remove(infohash)
            
            if DEBUG:
                print >>sys.stderr,"metadata: Was I asked to dlhelp someone",self.dlhelper

            self.notify_torrent_is_in(infohash,metadata,filename)
            
            
            # BarterCast: add bytes of torrent to BarterCastDB
            # Save exchanged KBs in BarterCastDB
            if permid != None and BARTERCAST_TORRENTS:
                self.overlay_bridge.add_task(lambda:self.olthread_bartercast_torrentexchange(permid, 'downloaded'), 0)
开发者ID:nomadsummer,项目名称:cs198mojo,代码行数:59,代码来源:MetadataHandler.py


示例9: get_signature

 def get_signature(self, data, config, signing_string):
     d = data.copy()
     d['merchant_id'] = config.merchant_id
     val1 = signing_string.format(**d)
     hash1 = sha.sha(val1).hexdigest()
     val2 = "{0}.{1}".format(hash1, config.shared_secret)
     hash2 = sha.sha(val2).hexdigest()
     return hash2
开发者ID:maanas,项目名称:merchant,代码行数:8,代码来源:global_iris_gateway.py


示例10: test_total_too_big

def test_total_too_big():
    ds = DummyStorage(9)
    try:
        sw = StorageWrapper(ds, 4, [sha('qqqq').digest(),
            sha(chr(0xFF) * 4).digest()], 4, ds.finished, None)
        raise 'fail'
    except ValueError:
        pass
开发者ID:BackupTheBerlios,项目名称:cbt-svn,代码行数:8,代码来源:StorageWrapper.py


示例11: rehash_voca

 def rehash_voca(self, maxw = -1):
     self._dhashvoca_F.clear()
     self._dhashvoca_R.clear()
     for i, x in enumerate(self.voca):
         if len(self._dhashvoca_F) == maxw:
             break
         self._dhashvoca_F[sha.sha(x[0].encode("utf-8")).hexdigest()[:8]] = i
         self._dhashvoca_R[sha.sha(x[2].encode("utf-8")).hexdigest()[:8]] = i
开发者ID:bthyreau,项目名称:japedict,代码行数:8,代码来源:displayer_srs_dropbox.py


示例12: test_total_too_short

def test_total_too_short():
    ds = DummyStorage(4)
    try:
        StorageWrapper(ds, 4, [sha(chr(0xff) * 4).digest(),
            sha(chr(0xFF) * 4).digest()], 4, ds.finished, None)
        raise 'fail'
    except ValueError:
        pass
开发者ID:BackupTheBerlios,项目名称:cbt-svn,代码行数:8,代码来源:StorageWrapper.py


示例13: compare_region

def compare_region(expected_region_file, got_region_file):
    # sha1 test for now, not great since regions can be permuted, but works for now
    f = open(expected_region_file, 'r')
    expected_sha1 = sha.sha(f.read()).hexdigest()
    f.close()
    f = open(got_region_file, 'r')
    got_sha1 = sha.sha(f.read()).hexdigest()
    f.close()
    return expected_sha1 == got_sha1
开发者ID:keflavich,项目名称:casa,代码行数:9,代码来源:test_boxit.py


示例14: test_copy

 def test_copy(self):
     import sha
     for repeat in [1, 10, 100]:
         d1 = rsha.sha("abc" * repeat)
         d2 = d1.copy()
         d1.update("def" * repeat)
         d2.update("gh" * repeat)
         assert d1.digest() == sha.sha("abc"*repeat+"def"*repeat).digest()
         assert d2.digest() == sha.sha("abc"*repeat+"gh"*repeat).digest()
开发者ID:Darriall,项目名称:pypy,代码行数:9,代码来源:test_rsha.py


示例15: user_preferences

def user_preferences(request, template_name='accounts/prefs.html'):
    redirect_to = request.REQUEST.get(REDIRECT_FIELD_NAME,
                                      reverse("dashboard"))

    profile, profile_is_new = \
        Profile.objects.get_or_create(user=request.user)
    must_configure = not profile.first_time_setup_done
    profile.save()

    siteconfig = SiteConfiguration.objects.get_current()
    auth_backend = siteconfig.get("auth_backend")
    can_change_password = auth_backend in ['builtin', 'x509']

    if request.POST:
        form = PreferencesForm(request.POST)

        if form.is_valid():
            password = form.cleaned_data['password1']

            if can_change_password and password:
                salt = sha(str(time.time())).hexdigest()[:5]
                hash = sha(salt + password)
                newpassword = 'sha1$%s$%s' % (salt, hash.hexdigest())
                request.user.password = newpassword

            if auth_backend == "builtin":
                request.user.first_name = form.cleaned_data['first_name']
                request.user.last_name = form.cleaned_data['last_name']
                request.user.email = form.cleaned_data['email']

            request.user.review_groups = form.cleaned_data['groups']
            request.user.save()

            profile.first_time_setup_done = True
            profile.syntax_highlighting = \
                form.cleaned_data['syntax_highlighting']
            profile.save()

            return HttpResponseRedirect(redirect_to)
    else:
        form = PreferencesForm({
            'settings': settings,
            'redirect_to': redirect_to,
            'first_name': request.user.first_name,
            'last_name': request.user.last_name,
            'email': request.user.email,
            'syntax_highlighting': profile.syntax_highlighting,
            'groups': [g.id for g in request.user.review_groups.all()],
        })

    return render_to_response(template_name, RequestContext(request, {
        'form': form,
        'settings': settings,
        'can_change_password': can_change_password,
        'must_configure': must_configure,
    }))
开发者ID:ChrisTrimble,项目名称:reviewboard,代码行数:56,代码来源:views.py


示例16: check_c14n_exc

 def check_c14n_exc(self):
     """http://www.w3.org/TR/xml-exc-c14n/
     """
     s = StringIO()
     Canonicalize(self.el, s, unsuppressedPrefixes=[])
     cxml = s.getvalue()
     d1 = base64.encodestring(sha.sha(C14N_EXCL1).digest()).strip()
     d2 = base64.encodestring(sha.sha(cxml).digest()).strip()
     self.assertEqual(d1, C14N_EXCL1_DIGEST)
     self.assertEqual(d1, d2)
开发者ID:360ed,项目名称:ZSI,代码行数:10,代码来源:test_t9.py


示例17: IncrementalOTA_VerifyEnd

def IncrementalOTA_VerifyEnd(info):
  target_radio_img = FindRadio(info.target_zip)
  source_radio_img = FindRadio(info.source_zip)
  if not target_radio_img or not source_radio_img: return
  if source_radio_img != target_radio_img:
    info.script.CacheFreeSpaceCheck(len(source_radio_img))
    radio_type, radio_device = common.GetTypeAndDevice("/radio", info.info_dict)
    info.script.PatchCheck("%s:%s:%d:%s:%d:%s" % (
        radio_type, radio_device,
        len(source_radio_img), sha.sha(source_radio_img).hexdigest(),
        len(target_radio_img), sha.sha(target_radio_img).hexdigest()))
开发者ID:ACSOP,项目名称:android_device_samsung_crespo,代码行数:11,代码来源:releasetools.py


示例18: create_wsse_token

def create_wsse_token(username, password):
  created = re.sub(u"\.\d+$", "", datetime.datetime.now().isoformat()) + "Z"
  nonce   = sha.sha(str(time.time() + random.random())).digest()
  digest  = sha.sha(nonce + created + password).digest()

  nonce64  = base64.b64encode(nonce)
  digest64 = base64.b64encode(digest)

  format = 'UsernameToken Username="%(u)s", PasswordDigest="%(p)s", Nonce="%(n)s", Created="%(c)s"'
  value  = dict(u = username, p = digest64, n = nonce64, c = created)
  return format % value
开发者ID:nayutaya,项目名称:ironnews-crawler,代码行数:11,代码来源:feeder_google_news.py


示例19: testOneWayBlast

    def testOneWayBlast(self, num = 2**12):
        a = self.a
        b = self.b
        
        import sha
        
        
        for i in xrange(num):
            a.omsgq.append(sha.sha(`i`).digest())
        runTillEmpty(a, b, noisy=self.noisy)

        self.assertEqual(len(b.protocol.q), num)
开发者ID:csm,项目名称:khashmir,代码行数:12,代码来源:test_airhook.py


示例20: doit

def doit(orig, mod, patchpath):
    origfiles = set([fn for fn in doscan(orig) if not os.path.isfile(os.path.join(mod, fn) + ".alwaysreplace")])
    modfiles = doscan(mod)
    commonfiles = origfiles.intersection(modfiles)
    newfiles = modfiles.difference(origfiles)
    filesnotneeded = origfiles.difference(modfiles)
    directories = set([os.path.dirname(entry) for entry in modfiles])

    try:
        os.mkdir(patchpath)
    except:
        print "Unable to create %s" % patchpath
        sys.exit(1)

    print "Checking for differences in %d common files, can take a while." % len(commonfiles)
    commonfiles = [cf for cf in commonfiles if (ourfcmp(cf, os.path.join(orig, cf), os.path.join(mod, cf), False) == False)]
    print "%d file(s) need patching." % len(commonfiles)

    f = open(os.path.join(patchpath, "modfiles.txt"), "wb")
    for fnn in modfiles:
        fnn_hash = sha.sha(open(os.path.join(mod, fnn), "rb").read()).hexdigest()
        f.write("%s %s\n" % (fnn, fnn_hash))
    f.close()

    f = open(os.path.join(patchpath, "tobepatched.txt"), "wb")
    for fnn in commonfiles:
        fnn_hash = sha.sha(open(os.path.join(mod, fnn), "rb").read()).hexdigest()
        f.write("%s %s\n" % (fnn, fnn_hash))
    f.close()

    f = open(os.path.join(patchpath, "newfiles.txt"), "wb")
    for fnn in newfiles:
        fnn_hash = sha.sha(open(os.path.join(mod, fnn), "rb").read()).hexdigest()
        f.write("%s %s\n" % (fnn, fnn_hash))
    f.close()

    f = open(os.path.join(patchpath, "directories.txt"), "wb")
    for fnn in directories:
        f.write(fnn)
        f.write("\n")
    f.close()

    print "Creating PATCHES for the other files"
    for pf in commonfiles:
        h = sha.sha(open(os.path.join(orig, pf), "rb").read()).hexdigest()
        mkpatch(os.path.join(orig, pf), os.path.join(mod, pf), os.path.join(patchpath, h + ".patch"))

    print "Copying NEW files to %s" % patchpath
    for nf in newfiles:
        nf_hash = sha.sha(open(os.path.join(mod, nf), 'rb').read()).hexdigest()
        print "%s => %s" % (nf, nf_hash)
        docopy(os.path.join(mod, nf), os.path.join(patchpath, nf_hash) + ".new")
开发者ID:hce,项目名称:dxvsetup,代码行数:52,代码来源:diffdirs.py



注:本文中的sha.sha函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python sha3.sha3_256函数代码示例发布时间:2022-05-27
下一篇:
Python sha.new函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap