我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用hashlib.sha512()。
def GetIntegrity(self, data): """Calculate the integirty value of given data using remote peers hash""" if self.hash_type == None: return None elif self.hash_type == 0: # SHA-1 return hashlib.sha1(data).digest() elif self.hash_type == 1: # SHA-224 return hashlib.sha224(data).digest() elif self.hash_type == 2: # SHA-256 return hashlib.sha256(data).digest() elif self.hash_type == 3: # SHA-384 return hashlib.sha384(data).digest() elif self.hash_type == 4: # SHA-512 return hashlib.sha512(data).digest() else: return None
def generate(password): '''Generate a ShadowHashData structure as used by macOS 10.8+''' iterations = arc4random.randrange(30000, 50000) salt = make_salt(32) keylen = 128 try: entropy = hashlib.pbkdf2_hmac( 'sha512', password, salt, iterations, dklen=keylen) except AttributeError: # old Python, do it a different way entropy = pbkdf2.pbkdf2_bin( password, salt, iterations=iterations, keylen=keylen, hashfunc=hashlib.sha512) data = {'SALTED-SHA512-PBKDF2': {'entropy': buffer(entropy), 'iterations': iterations, 'salt': buffer(salt)}, } return plistutils.write_plist(data, plist_format='binary')
def get_hashsums(file_path): hash_sums = od() hash_sums['md5sum'] = hashlib.md5() hash_sums['sha1sum'] = hashlib.sha1() hash_sums['sha224sum'] = hashlib.sha224() hash_sums['sha256sum'] = hashlib.sha256() hash_sums['sha384sum'] = hashlib.sha384() hash_sums['sha512sum'] = hashlib.sha512() with open(file_path, 'rb') as fd: data_chunk = fd.read(1024) while data_chunk: for hashsum in hash_sums.keys(): hash_sums[hashsum].update(data_chunk) data_chunk = fd.read(1024) results = od() for key,value in hash_sums.items(): results[key] = value.hexdigest() return results
def get_digest(value): """Return a hashlib digest algorithm from a string.""" if not isinstance(value, str): return value value = value.lower() if value == "md5": return md5 elif value == "sha1": return sha1 elif value == "sha224": return sha224 elif value == "sha256": return sha256 elif value == "sha384": return sha384 elif value == "sha512": return sha512 else: raise ValueError("Invalid digest algorithm: %s" % value)
def get_digest(value): """ Returns a hashlib digest algorithm from a string """ if not isinstance(value, str): return value value = value.lower() if value == "md5": return hashlib.md5 elif value == "sha1": return hashlib.sha1 elif value == "sha224": return hashlib.sha224 elif value == "sha256": return hashlib.sha256 elif value == "sha384": return hashlib.sha384 elif value == "sha512": return hashlib.sha512 else: raise ValueError("Invalid digest algorithm: %s" % value)
def auth_local(self, username, password): password = hashlib.sha512(password.encode('utf-8')).hexdigest() user = User.query.filter_by(username = username).first() if (user == None): return {"success":'false', "reason": "User did not exist"} if (user.password != password): return {"success":'false', "reason": "Wrong password"} result = { "success": 'true', "data":{ "username" : user.username, "avatar" : user.avatar, "nickname" : user.nickname, "description" : user.description, "status" : user.status, "group" : user.user_group, "token" : user.generate_auth_token(), } } return result
def hash_iterative(s, n, k): ''' Uses Hashing technique mentioned in BLISS pg 19 i/p: string s to be hashed to binary string of length n and weight k ''' i = 0 # seed which increases till we get Bk^n while(True): Bk = [0] * n I_val = int(hashlib.sha512(s + str(i)).hexdigest(), 16) count = 0 while(I_val > 0): pos = I_val % n I_val /= n if(Bk[pos] == 0): Bk[pos] = 1 count += 1 if(count == k): return np.array(Bk) i += 1
def read_tar(f): result = {} try: with tarfile.open(f) as t: for m in t: if m.isfile(): f = t.extractfile(m) sha512 = sha512_file(f) else: sha512 = None result[m.name] = TarMemberInfo(m, sha512) except tarfile.ReadError: # if we can't read the tar archive, we should never consider it to have # the same contents as another tar archive... result[f] = None return result # # #
def read_packages(rel_area, arch): packages = defaultdict(Package) # <arch>/ noarch/ and src/ directories are considered for root in ['noarch', 'src', arch]: releasedir = os.path.join(rel_area, root) logging.debug('reading packages from %s' % releasedir) for (dirpath, subdirs, files) in os.walk(releasedir, followlinks=True): read_package(packages, rel_area, dirpath, files) logging.debug("%d packages read" % len(packages)) return packages # helper function to compute sha512 for a particular file # (block_size should be some multiple of sha512 block size which can be efficiently read)
def get_mosfit_hash(salt=u''): """Return a unique hash for the MOSFiT code.""" import fnmatch import os dir_path = os.path.dirname(os.path.realpath(__file__)) matches = [] for root, dirnames, filenames in os.walk(dir_path): for filename in fnmatch.filter(filenames, '*.py'): matches.append(os.path.join(root, filename)) matches = list(sorted(list(matches))) code_str = salt for match in matches: with codecs.open(match, 'r', 'utf-8') as f: code_str += f.read() return hashlib.sha512(hash_bytes(code_str)).hexdigest()[:16]
def query_private(self, method, req={}, conn = None): """API queries that require a valid key/secret pair. Arguments: method -- API method name (string, no default) req -- additional API request parameters (default: {}) conn -- connection object to reuse (default: None) """ urlpath = '/' + self.apiversion + '/private/' + method req['nonce'] = int(1000*time.time()) postdata = urllib.urlencode(req) message = urlpath + hashlib.sha256(str(req['nonce']) + postdata).digest() signature = hmac.new(base64.b64decode(self.secret), message, hashlib.sha512) headers = { 'API-Key': self.key, 'API-Sign': base64.b64encode(signature.digest()) } return self._query(urlpath, req, conn, headers)
def decrypt(self, data, ciphername='aes-256-cbc'): """ Decrypt data with ECIES method using the local private key """ blocksize = OpenSSL.get_cipher(ciphername).get_blocksize() iv = data[:blocksize] i = blocksize curve, pubkey_x, pubkey_y, i2 = ECC._decode_pubkey(data[i:]) i += i2 ciphertext = data[i:len(data)-32] i += len(ciphertext) mac = data[i:] key = sha512(self.raw_get_ecdh_key(pubkey_x, pubkey_y)).digest() key_e, key_m = key[:32], key[32:] if not equals(hmac_sha256(key_m, data[:len(data) - 32]), mac): raise RuntimeError("Fail to verify data") ctx = Cipher(key_e, iv, 0, ciphername) return ctx.ciphering(ciphertext)
def malware_sample(): sampledata = BytesIO(b'clean') buf = sampledata.read() sampledata.seek(0) md5_hash = hashlib.md5(buf).hexdigest() sha1_hash = hashlib.sha1(buf).hexdigest() sha256_hash = hashlib.sha256(buf).hexdigest() sha512_hash = hashlib.sha512(buf).hexdigest() ctph = ssdeep.hash(buf) Sample = namedtuple( 'Sample', ['data', 'filename', 'md5', 'sha1', 'sha256', 'sha512', 'ctph']) sample = Sample( data='sampledata', filename='blah.zip', md5=md5_hash, sha1=sha1_hash, sha256=sha256_hash, sha512=sha512_hash, ctph=ctph) return sample
def _call(self, topic: str, args: dict() = {}): if topic in ['returnTicker', 'return24Volume', 'returnOrderBook', 'returnTradeHistory', 'returnChartData', 'returnCurrencies', 'returnLoanOrders']: api = [self.public_url, 'get', topic] else: api = [self.private_url, 'post', topic, self.secrets] def __call(api_details, uri): request = getattr(requests, api_details[1]) headers = {} del uri['self'] uri['command'] = api_details[2] if api_details[2] == 'post': uri['nonce'] = int(time.time() * 1000) sign = hmac.new(api_details[3]['secret'], uri, hashlib.sha512).hexdigest() headers['Sign'] = sign headers['Key'] = api_details[3]['api_key'] return json.loads(request(api_details[0], uri, headers=headers).content.decode()) with self.limiter: return __call(api, args)
def hashPasswordTuple(password, digestMod=hashlib.sha512, iterations=10000, saltSize=32): """ Module function to hash a password according to the PBKDF2 specification. @param password clear text password (string) @param digestMod hash function @param iterations number of times hash function should be applied (integer) @param saltSize size of the salt (integer) @return tuple of digestname (string), number of iterations (integer), salt (bytes) and hashed password (bytes) """ salt = os.urandom(saltSize) password = password.encode("utf-8") hash = pbkdf2(password, salt, iterations, digestMod) digestname = digestMod.__name__.replace("openssl_", "") return digestname, iterations, salt, hash
def hashPassword(password, digestMod=hashlib.sha512, iterations=10000, saltSize=32): """ Module function to hash a password according to the PBKDF2 specification. @param password clear text password (string) @param digestMod hash function @param iterations number of times hash function should be applied (integer) @param saltSize size of the salt (integer) @return hashed password entry according to PBKDF2 specification (string) """ digestname, iterations, salt, hash = \ hashPasswordTuple(password, digestMod, iterations, saltSize) return Delimiter.join([ digestname, str(iterations), base64.b64encode(salt).decode("ascii"), base64.b64encode(hash).decode("ascii") ])
def get_shared_secret(priv, pub): """ Derive the share secret between ``priv`` and ``pub`` :param `Base58` priv: Private Key :param `Base58` pub: Public Key :return: Shared secret :rtype: hex The shared secret is generated such that:: Pub(Alice) * Priv(Bob) = Pub(Bob) * Priv(Alice) """ pub_point = pub.point() priv_point = int(repr(priv), 16) res = pub_point * priv_point res_hex = '%032x' % res.x() # Zero padding res_hex = '0' * (64 - len(res_hex)) + res_hex return hashlib.sha512(unhexlify(res_hex)).hexdigest()
def init_aes(shared_secret, nonce): """ Initialize AES instance :param hex shared_secret: Shared Secret to use as encryption key :param int nonce: Random nonce :return: AES instance and checksum of the encryption key :rtype: length 2 tuple """ " Seed " ss = unhexlify(shared_secret) n = struct.pack("<Q", int(nonce)) encryption_key = hashlib.sha512(n + ss).hexdigest() " Check'sum' " check = hashlib.sha256(unhexlify(encryption_key)).digest() check = struct.unpack_from("<I", check[:4])[0] " AES " key = unhexlify(encryption_key[0:64]) iv = unhexlify(encryption_key[64:96]) return AES.new(key, AES.MODE_CBC, iv), check
def sign(self, url, endpoint, endpoint_path, method_verb, *args, **kwargs): try: req = kwargs['params'] except KeyError: req = {} req['nonce'] = self.nonce() postdata = urllib.parse.urlencode(req) # Unicode-objects must be encoded before hashing encoded = (str(req['nonce']) + postdata).encode('utf-8') message = (endpoint_path.encode('utf-8') + hashlib.sha256(encoded).digest()) signature = hmac.new(base64.b64decode(self.secret), message, hashlib.sha512) sigdigest = base64.b64encode(signature.digest()) headers = { 'API-Key': self.key, 'API-Sign': sigdigest.decode('utf-8') } return url, {'data': req, 'headers': headers}
def sign(self, uri, endpoint, endpoint_path, method_verb, *args, **kwargs): nonce = self.nonce() try: params = kwargs['params'] except KeyError: params = {} params['apikey'] = self.key params['nonce'] = nonce post_params = params post_params.update({'nonce': nonce, 'method': endpoint}) post_params = urllib.parse.urlencode(post_params) url = uri + post_params sig = hmac.new(url, self.secret, hashlib.sha512) headers = {'apisign': sig} return url, {'headers': headers}
def sign(self, url, endpoint, endpoint_path, method_verb, *args, **kwargs): try: params = kwargs['params'] except KeyError: params = {} nonce = self.nonce() req_string = endpoint_path + '?apikey=' + self.key + "&nonce=" + nonce + '&' req_string += urllib.parse.urlencode(params) headers = {"apisign": hmac.new(self.secret.encode('utf-8'), (self.uri + req_string).encode('utf-8'), hashlib.sha512).hexdigest()} return self.uri + req_string, {'headers': headers, 'params': {}}
def sign(self, payload): """ Signature method which wraps signature and nonce parameters around a payload dictionary. :param payload: :return: """ nonce = str(int(time.time() * 1000)) package = {'apikey': self.key, 'message': {'nonce': nonce, 'payload': payload}} signature = hmac.new(self.secret, json.dumps(payload).hexdigest, hashlib.sha512).hexdigest() package['signature'] = signature return json.dumps(package)
def __call__(self, r): r.headers["Content-type"] = "application/x-www-form-urlencoded" r.headers["API-Key"] = self.key.replace(" ", "+") urlpath = '/0/private/' + self.method postdata = urllib.urlencode(self.params) #print "params:", self.params #print "nonce:", self.params["nonce"] message = urlpath + hashlib.sha256(str(self.params["nonce"]) + postdata).digest() #print message signature = hmac.new(base64.b64decode(self.secret.replace(" ", "+")), message, hashlib.sha512) r.headers["API-Sign"] = base64.b64encode(signature.digest()) #print r.headers return r
def master_key_from_seed(seed): """ Generates a master key from a provided seed. Args: seed (bytes or str): a string of bytes or a hex string Returns: HDPrivateKey: the master private key. """ S = get_bytes(seed) I = hmac.new(b"Bitcoin seed", S, hashlib.sha512).digest() Il, Ir = I[:32], I[32:] parse_Il = int.from_bytes(Il, 'big') if parse_Il == 0 or parse_Il >= bitcoin_curve.n: raise ValueError("Bad seed, resulting in invalid key!") return HDPrivateKey(key=parse_Il, chain_code=Ir, index=0, depth=0)
def H(m): return hashlib.sha512(m).digest()
def seed(self, a=None, version=2): """Initialize internal state from hashable object. None or no argument seeds from current time or from an operating system specific randomness source if available. If *a* is an int, all bits are used. For version 2 (the default), all of the bits are used if *a* is a str, bytes, or bytearray. For version 1 (provided for reproducing random sequences from older versions of Python), the algorithm for str and bytes generates a narrower range of seeds. """ if version == 1 and isinstance(a, (str, bytes)): x = ord(a[0]) << 7 if a else 0 for c in a: x = ((1000003 * x) ^ ord(c)) & 0xFFFFFFFFFFFFFFFF x ^= len(a) a = -2 if x == -1 else x if version == 2 and isinstance(a, (str, bytes, bytearray)): if isinstance(a, str): a = a.encode() a += _sha512(a).digest() a = int.from_bytes(a, 'big') super().seed(a) self.gauss_next = None
def selfModify(*args, **kwargs): ''' Usage: selfModify(cur_user = token_from_auth, newValue = form) Modify informantion for oneself ''' form = kwargs['newValue'] name = form.get('name', None) value = form.get('value', None) if (name == None or value == None): result = {'success': 'false'} return result user = User.query.filter_by(username = kwargs['cur_user'].username).first() if (name == 'nickname'): user.nickname = value elif (name == 'description'): user.description = value elif (name == 'department'): user.department = value elif (name == 'e_mail'): user.e_mail = value elif (name == 'tel'): user.tel = value elif (name == 'password'): old_password = hashlib.sha512(form.get('old_value', '').encode('utf-8')).hexdigest() if (user.password != old_password): result = {'success': 'false'} return result user.password = hashlib.sha512(value.encode('utf-8')).hexdigest() else: result = {'success': 'false'} return result db.session.commit() result = {'success': 'true'} return result
def chpassword(*args, **kwargs): ''' Usage: chpassword(cur_user = token_from_auth, password = 'your_password') ''' cur_user = kwargs['cur_user'] cur_user.password = hashlib.sha512(kwargs['password'].encode('utf-8')).hexdigest()
def register(self, *args, **kwargs): ''' Usage: register(user = modified_from_newuser()) ''' if (kwargs['user'].username == None or kwargs['user'].username == ''): return {"success":'false', "reason": "Empty username"} user_check = User.query.filter_by(username = kwargs['user'].username).first() if (user_check != None and user_check.status != "init"): #for the activating form return {"success":'false', "reason": "Unauthorized action"} newuser = kwargs['user'] if (user_check != None and (user_check.status == "init")): db.session.delete(user_check) db.session.commit() else: newuser.password = hashlib.sha512(newuser.password.encode('utf-8')).hexdigest() db.session.add(newuser) db.session.commit() # if newuser status is normal, init some data for this user # now initialize for all kind of users #if newuser.status == 'normal': path = env.getenv('DOCKLET_LIB') subprocess.call([path+"/userinit.sh", newuser.username]) res = self.groupQuery(name=newuser.user_group) if res['success']: self.set_nfs_quota(newuser.username,res['data']['data']) return {"success":'true'}
def api_query(self, command, req={}): if (command == "returnTicker" or command == "return24Volume"): ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=' + command)) return json.loads(ret.read()) elif (command == "returnOrderBook"): ret = urllib2.urlopen(urllib2.Request( 'https://poloniex.com/public?command=' + command + '¤cyPair=' + str(req['currencyPair']))) return json.loads(ret.read()) elif (command == "returnMarketTradeHistory"): ret = urllib2.urlopen(urllib2.Request( 'https://poloniex.com/public?command=' + "returnTradeHistory" + '¤cyPair=' + str( req['currencyPair']))) return json.loads(ret.read()) else: req['command'] = command req['nonce'] = int(time.time() * 1000) post_data = urllib.urlencode(req) sign = hmac.new(self.Secret, post_data, hashlib.sha512).hexdigest() headers = { 'Sign': sign, 'Key': self.APIKey } ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/tradingApi', post_data, headers)) jsonRet = json.loads(ret.read()) return self.post_process(jsonRet)
def H(x): # random oracle h = int(hashlib.sha512(str(x)).hexdigest(), 16) out = vector([0]*k, Zmod(q)) for i in range(0, k) : out[i] = h%b h /= b i += 1 return out
def hash_to_baseb(matrix, message, b, k): ''' i/p: matrix : numpy array to be hashed message : string that the sender sends o/p: list with k elements each b/w 0 to b-1 ''' hexval = hl.sha512(np.array_str(matrix) + message).hexdigest() # returns a string with 128 hex digits return np.array(map(int, list(b2b(hexval, 16, b)[:k]))) # returns first k digits from hexval in a list # this list of symbols allows conversion of numbers represented until base 36
def create (seed, hash=hashlib.sha512): """Create a new TOTP for the given secret seed and hash, using the default 30 second time step period.""" return totp(stringToHex(seed), format='dec8', hash=hash)
def api_query(self, method, options=None): """ Queries Bittrex with given method and options :param method: Query method for getting info :type method: str :param options: Extra options for query :type options: dict :return: JSON response from Bittrex :rtype : dict """ if not options: options = {} nonce = str(int(time.time() * 1000)) method_set = 'public' if method in MARKET_SET: method_set = 'market' elif method in ACCOUNT_SET: method_set = 'account' request_url = (BASE_URL % method_set) + method + '?' if method_set != 'public': request_url += 'apikey=' + self.api_key + "&nonce=" + nonce + '&' request_url += urlencode(options) return requests.get( request_url, headers={"apisign": hmac.new(self.api_secret.encode(), request_url.encode(), hashlib.sha512).hexdigest()} ).json()
def api_query(self, command, req={}): if(command == "returnTicker" or command == "return24Volume"): ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=' + command)) return json.loads(ret.read()) elif(command == "returnOrderBook"): ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=' + command + '¤cyPair=' + str(req['currencyPair']))) return json.loads(ret.read()) elif(command == "returnMarketTradeHistory"): ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=' + "returnTradeHistory" + '¤cyPair=' + str(req['currencyPair']))) return json.loads(ret.read()) elif (command == "returnChartData"): ret = urllib2.urlopen(urllib2.Request( 'https://poloniex.com/public?command=' + "returnChartData" + '¤cyPair=' + str( req['currencyPair']) + '&start=' + str( req['start']) + '&end=' + str( req['end']) + '&period=' + str(req['period']))) return json.loads(ret.read()) else: req['command'] = command req['nonce'] = int(time.time()*1000) post_data = urllib.urlencode(req) sign = hmac.new(self.Secret, post_data, hashlib.sha512).hexdigest() headers = { 'Sign': sign, 'Key': self.APIKey } ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/tradingApi', post_data, headers)) jsonRet = json.loads(ret.read()) return self.post_process(jsonRet)
def make_secure_token(*args, **options): ''' This will create a secure token that you can use as an authentication token for your users. It uses heavy-duty HMAC encryption to prevent people from guessing the information. (To make it even more effective, if you will never need to regenerate the token, you can pass some random data as one of the arguments.) :param \*args: The data to include in the token. :type args: args :param \*\*options: To manually specify a secret key, pass ``key=THE_KEY``. Otherwise, the ``current_app`` secret key will be used. :type \*\*options: kwargs ''' key = options.get('key') key = _secret_key(key) l = [s if isinstance(s, bytes) else s.encode('utf-8') for s in args] payload = b'\0'.join(l) token_value = hmac.new(key, payload, sha512).hexdigest() if hasattr(token_value, 'decode'): # pragma: no cover token_value = token_value.decode('utf-8') # ensure bytes return token_value
def _cookie_digest(payload, key=None): key = _secret_key(key) return hmac.new(key, payload.encode('utf-8'), sha512).hexdigest()
def _create_identifier(): user_agent = request.headers.get('User-Agent') if user_agent is not None: user_agent = user_agent.encode('utf-8') base = '{0}|{1}'.format(_get_remote_addr(), user_agent) if str is bytes: base = unicode(base, 'utf-8', errors='replace') # pragma: no cover h = sha512() h.update(base.encode('utf8')) return h.hexdigest()
def save(obj): """return inner state of sha512 `obj` as raw string""" #assert isinstance(obj, sha512) datap = ctypes.cast(ctypes.cast(id(obj), ctypes.POINTER(ctypes.c_voidp))[POFFSET], ctypes.POINTER(ctypes.c_char)) assert datap return datap[:STATESIZE]
def restore(data): """create new sha512 object with inner state from `data`, str/bytes or iterable""" new = sha512() datap = ctypes.cast(ctypes.cast(id(new), ctypes.POINTER(ctypes.c_voidp))[POFFSET], ctypes.POINTER(ctypes.c_char)) assert datap assert datap[:8] == '\x08\xc9\xbc\xf3g\xe6\tj' # first sha512 word for i, byte in enumerate(data): assert i < STATESIZE datap[i] = byte assert i + 1 == STATESIZE return new
def encode_sha512(self, *, message : str): '''Generate SHA-512 hash''' await self.bot.embed_reply(hashlib.sha512(message.encode("utf-8")).hexdigest())