我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sha.sha()。
def mangleData(self, data, index): self.sha1_offset = 208 self.md5_offset = 256 self.header_offset = 360 self.filedata_offset = 3170 data = MangleFile.mangleData(self, data, index) if USE_HACHOIR: #data.tofile(open('/tmp/oops', 'wb')) hachoir_config.quiet = True data_str = data.tostring() parser = guessParser(StringInputStream(data_str)) if parser: self.useHachoirParser(parser) summary_data = data[self.header_offset:].tostring() checksum = md5(summary_data).digest() data[self.md5_offset:self.md5_offset+16] = array('B', checksum) summary_data = data[self.header_offset:self.filedata_offset].tostring() checksum = sha(summary_data).hexdigest() data[self.sha1_offset:self.sha1_offset+40] = array('B', checksum) return data
def secure_hash(filename, hash_func=sha1): ''' Return a secure hash hex digest of local file, None if file is not present or a directory. ''' if not os.path.exists(to_bytes(filename, errors='surrogate_or_strict')) or os.path.isdir(to_bytes(filename, errors='strict')): return None digest = hash_func() blocksize = 64 * 1024 try: infile = open(to_bytes(filename, errors='surrogate_or_strict'), 'rb') block = infile.read(blocksize) while block: digest.update(block) block = infile.read(blocksize) infile.close() except IOError as e: raise AnsibleError("error while accessing the file %s, error was: %s" % (filename, e)) return digest.hexdigest() # The checksum algorithm must match with the algorithm in ShellModule.checksum() method
def __init__(self, token, request, post_data={}, **kwargs): for key, value in kwargs.items(): setattr(self, key, value) self.tries = 0 self.start_time = time.time() self.domain = 'api.slack.com' self.request = request self.request_normalized = re.sub(r'\W+', '', request) self.token = token post_data["token"] = token self.post_data = post_data self.params = {'useragent': 'wee_slack {}'.format(SCRIPT_VERSION)} self.url = 'https://{}/api/{}?{}'.format(self.domain, request, urllib.urlencode(encode_to_utf8(post_data))) self.response_id = sha.sha("{}{}".format(self.url, self.start_time)).hexdigest() self.retries = kwargs.get('retries', 3) # def __repr__(self): # return "URL: {} Tries: {} ID: {}".format(self.url, self.tries, self.response_id)
def __init__(self, loader=None, inventory=None): self._nonpersistent_fact_cache = defaultdict(dict) self._vars_cache = defaultdict(dict) self._extra_vars = defaultdict(dict) self._host_vars_files = defaultdict(dict) self._group_vars_files = defaultdict(dict) self._inventory = inventory self._loader = loader self._hostvars = None self._omit_token = '__omit_place_holder__%s' % sha1(os.urandom(64)).hexdigest() self._options_vars = defaultdict(dict) # bad cache plugin is not fatal error try: self._fact_cache = FactCache() except AnsibleError as e: display.warning(to_native(e)) # fallback to a dict as in memory cache self._fact_cache = {}
def _mint(challenge, bits): """Answer a 'generalized hashcash' challenge' Hashcash requires stamps of form 'ver:bits:date:res:ext:rand:counter' This internal function accepts a generalized prefix 'challenge', and returns only a suffix that produces the requested SHA leading zeros. NOTE: Number of requested bits is rounded up to the nearest multiple of 4 """ counter = 0 hex_digits = int(ceil(bits/4.)) zeros = '0'*hex_digits while 1: digest = sha(challenge+hex(counter)[2:]).hexdigest() if digest[:hex_digits] == zeros: tries[0] = counter return hex(counter)[2:] counter += 1
def url_processor_cb(data, command, return_code, out, err): global big_data data = pickle.loads(data) identifier = sha.sha("{}{}".format(data, command)).hexdigest() if identifier not in big_data: big_data[identifier] = '' big_data[identifier] += out if return_code == 0: try: my_json = json.loads(big_data[identifier]) except: dbg("request failed, doing again...") dbg("response length: {} identifier {}\n{}".format(len(big_data[identifier]), identifier, data)) my_json = False big_data.pop(identifier, None) if my_json: if data["request"] == 'rtm.start': servers.find(data["token"]).connected_to_slack(my_json) servers.update_hashtable() else: if "channel" in data["post_data"]: channel = data["post_data"]["channel"] token = data["token"] if "messages" in my_json: messages = my_json["messages"].reverse() for message in my_json["messages"]: message["_server"] = servers.find(token).domain message["channel"] = servers.find(token).channels.find(channel).identifier process_message(message) if "channel" in my_json: if "members" in my_json["channel"]: channels.find(my_json["channel"]["id"]).members = set(my_json["channel"]["members"]) else: if return_code != -1: big_data.pop(identifier, None) dbg("return code: {}, data: {}, output: {}, error: {}".format(return_code, data, out, err)) return w.WEECHAT_RC_OK
def __init__(self, title): self.title = title self.filename = None self.headcomments = "" self.campaign = [] self.keywords = [] self.crc = None self.sha = None self.preexec = None self.preexec_output = None
def dump_campaign(test_campaign): print "#"*(len(test_campaign.title)+6) print "## %(title)s ##" % test_campaign print "#"*(len(test_campaign.title)+6) if test_campaign.sha and test_campaign.crc: print "CRC=[%(crc)s] SHA=[%(sha)s]" % test_campaign print "from file %(filename)s" % test_campaign print for ts in test_campaign: if ts.crc: print "+--[%s]%s(%s)--" % (ts.name,"-"*max(2,80-len(ts.name)-18),ts.crc) else: print "+--[%s]%s" % (ts.name,"-"*max(2,80-len(ts.name)-6)) if ts.keywords: print " kw=%s" % ",".join(ts.keywords) for t in ts: print "%(num)03i %(name)s" % t c = k = "" if t.keywords: k = "kw=%s" % ",".join(t.keywords) if t.crc: c = "[%(crc)s] " % t if c or k: print " %s%s" % (c,k) #### COMPUTE CAMPAIGN DIGESTS ####
def sha1(x): return sha.sha(x).hexdigest().upper()
def compute_campaign_digests(test_campaign): dc = "" for ts in test_campaign: dts = "" for t in ts: dt = t.test.strip() t.crc = crc32(dt) dts += "\0"+dt ts.crc = crc32(dts) dc += "\0\x01"+dts test_campaign.crc = crc32(dc) test_campaign.sha = sha1(open(test_campaign.filename).read()) #### FILTER CAMPAIGN #####
def run_campaign(test_campaign, get_interactive_session, verb=2): passed=failed=0 if test_campaign.preexec: test_campaign.preexec_output = get_interactive_session(test_campaign.preexec.strip())[0] for testset in test_campaign: for t in testset: t.output,res = get_interactive_session(t.test.strip()) the_res = False try: if res is None or res: the_res= True except Exception,msg: t.output+="UTscapy: Error during result interpretation:\n" t.output+="".join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback,)) if the_res: t.res = True res = "passed" passed += 1 else: t.res = False res = "failed" failed += 1 t.result = res if verb > 1: print >>sys.stderr,"%(result)6s %(crc)s %(name)s" % t test_campaign.passed = passed test_campaign.failed = failed if verb: print >>sys.stderr,"Campaign CRC=%(crc)s SHA=%(sha)s" % test_campaign print >>sys.stderr,"PASSED=%i FAILED=%i" % (passed, failed) #### INFO LINES ####
def PRF(secret, label, seed, length): #Split the secret into left and right halves S1 = secret[ : int(math.ceil(len(secret)/2.0))] S2 = secret[ int(math.floor(len(secret)/2.0)) : ] #Run the left half through P_MD5 and the right half through P_SHA1 p_md5 = P_hash(md5, S1, concatArrays(stringToBytes(label), seed), length) p_sha1 = P_hash(sha, S2, concatArrays(stringToBytes(label), seed), length) #XOR the output values and return the result for x in range(length): p_md5[x] ^= p_sha1[x] return p_md5
def PRF_SSL(secret, seed, length): secretStr = bytesToString(secret) seedStr = bytesToString(seed) bytes = createByteArrayZeros(length) index = 0 for x in range(26): A = chr(ord('A')+x) * (x+1) # 'A', 'BB', 'CCC', etc.. input = secretStr + sha.sha(A + secretStr + seedStr).digest() output = md5.md5(input).digest() for c in output: if index >= length: return bytes bytes[index] = ord(c) index += 1 return bytes
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()) #This function is used by VerifierDB.makeVerifier
def makeU(N, A, B): return stringToNumber(sha.sha(PAD(N, A) + PAD(N, B)).digest())
def makeK(N, g): return stringToNumber(sha.sha(numberToString(N) + PAD(N, g)).digest())
def _handshakeStart(self, client): self._client = client self._handshake_md5 = md5.md5() self._handshake_sha = sha.sha() self._handshakeBuffer = [] self.allegedSharedKeyUsername = None self.allegedSrpUsername = None self._refCount = 1
def _calcSSLHandshakeHash(self, masterSecret, label): masterSecretStr = bytesToString(masterSecret) imac_md5 = self._handshake_md5.copy() imac_sha = self._handshake_sha.copy() imac_md5.update(label + masterSecretStr + '\x36'*48) imac_sha.update(label + masterSecretStr + '\x36'*40) md5Str = md5.md5(masterSecretStr + ('\x5c'*48) + \ imac_md5.digest()).digest() shaStr = sha.sha(masterSecretStr + ('\x5c'*40) + \ imac_sha.digest()).digest() return stringToBytes(md5Str + shaStr)
def hash(self, clientRandom, serverRandom): oldCipherSuite = self.cipherSuite self.cipherSuite = None try: bytes = clientRandom + serverRandom + self.write()[4:] s = bytesToString(bytes) return stringToBytes(md5.md5(s).digest() + sha.sha(s).digest()) finally: self.cipherSuite = oldCipherSuite
def getSHA1(s): return sha.sha(s)
def getSHA1(s): #return JCE_SHA1(s) return sha.sha(s) #Adjust the string to an array of bytes
def get_basename(text, options, prefix='aafig'): options = options.copy() if 'format' in options: del options['format'] hashkey = text + str(options) _id = sha(hashkey.encode('utf-8')).hexdigest() return '%s-%s' % (prefix, _id)
def get_basename(text, options, prefix='aafig'): options = options.copy() if 'format' in options: del options['format'] hashkey = text.encode('utf-8') + str(options) id = sha(hashkey).hexdigest() return '%s-%s' % (prefix, id)
def __getitem__(self, host_name): data = self.raw_get(host_name) sha1_hash = sha1(str(data).encode('utf-8')).hexdigest() if sha1_hash in self._cached_result: result = self._cached_result[sha1_hash] else: templar = Templar(variables=data, loader=self._loader) result = templar.template(data, fail_on_undefined=False, static_vars=STATIC_VARS) self._cached_result[sha1_hash] = result return result
def __init__(self): self._fact_cache = FactCache() self._nonpersistent_fact_cache = defaultdict(dict) self._vars_cache = defaultdict(dict) self._extra_vars = defaultdict(dict) self._host_vars_files = defaultdict(dict) self._group_vars_files = defaultdict(dict) self._inventory = None self._hostvars = None self._omit_token = '__omit_place_holder__%s' % sha1(os.urandom(64)).hexdigest() self._options_vars = defaultdict(dict)
def __setstate__(self, data): self._fact_cache = data.get('fact_cache', defaultdict(dict)) self._nonpersistent_fact_cache = data.get('np_fact_cache', defaultdict(dict)) self._vars_cache = data.get('vars_cache', defaultdict(dict)) self._extra_vars = data.get('extra_vars', dict()) self._host_vars_files = data.get('host_vars_files', defaultdict(dict)) self._group_vars_files = data.get('group_vars_files', defaultdict(dict)) self._omit_token = data.get('omit_token', '__omit_place_holder__%s' % sha1(os.urandom(64)).hexdigest()) self._inventory = data.get('inventory', None) self._options_vars = data.get('options_vars', dict())
def secure_hash_s(data, hash_func=sha1): ''' Return a secure hash hex digest of data. ''' digest = hash_func() data = to_bytes(data, errors='surrogate_or_strict') digest.update(data) return digest.hexdigest()
def run_campaign(test_campaign, get_interactive_session, verb=2): passed=failed=0 if test_campaign.preexec: test_campaign.preexec_output = get_interactive_session(test_campaign.preexec.strip())[0] for testset in test_campaign: for t in testset: t.output,res = get_interactive_session(t.test.strip()) the_res = False try: if res is None or res: the_res= True except Exception,msg: t.output+="UTscapy: Error during result interpretation:\n" t.output+="".join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback,)) if the_res: t.res = True res = "passed" passed += 1 else: t.res = False res = "failed" failed += 1 t.result = res if verb > 1: print >>sys.stderr,"%(result)6s %(crc)s %(name)s" % t test_campaign.passed = passed test_campaign.failed = failed if verb: print >>sys.stderr,"Campaign CRC=%(crc)s SHA=%(sha)s" % test_campaign print >>sys.stderr,"PASSED=%i FAILED=%i" % (passed, failed) return failed #### INFO LINES ####