本文整理汇总了Python中hashlib.blake2b方法的典型用法代码示例。如果您正苦于以下问题:Python hashlib.blake2b方法的具体用法?Python hashlib.blake2b怎么用?Python hashlib.blake2b使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类hashlib
的用法示例。
在下文中一共展示了hashlib.blake2b方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _get_hashes
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import blake2b [as 别名]
def _get_hashes(path: Path) -> Dict[str, str]:
sha256_manager = hashlib.sha256()
md5_manager = hashlib.md5()
if hasattr(hashlib, 'blake2b'):
blake2_manager = hashlib.blake2b(digest_size=32)
else:
blake2_manager = None
with path.open('rb') as stream:
while True:
data = stream.read(65536)
if not data:
break
sha256_manager.update(data)
md5_manager.update(data)
if blake2_manager:
blake2_manager.update(data)
return dict(
md5_digest=md5_manager.hexdigest(),
sha256_digest=sha256_manager.hexdigest(),
blake2_256_digest=blake2_manager.hexdigest(),
)
示例2: test_hash_same_as_nonchunked
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import blake2b [as 别名]
def test_hash_same_as_nonchunked(self, event_loop, mock_dataset_with_manifest):
ds, manifest, working_dir = mock_dataset_with_manifest
sh = SmartHash(ds.root_dir, manifest.cache_mgr.cache_root, manifest.dataset_revision)
cache_dir = manifest.cache_mgr.cache_root
revision = manifest.dataset_revision
filename = "test1.txt"
helper_append_file(cache_dir, revision, filename, "asdfdsfgkdfshuhwedfgft345wfd" * 100000)
assert sh.fast_hash_data == {}
assert sh.is_cached(filename) is False
assert os.path.exists(os.path.join(cache_dir, revision, ".smarthash")) is False
hash_result = await sh.hash([filename])
hash_result = hash_result[0]
h = blake2b()
with open(sh.get_abs_path(filename), 'rb') as fh:
h.update(fh.read())
assert hash_result == h.hexdigest()
示例3: __init__
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import blake2b [as 别名]
def __init__(self, code: str, key: bytes, ns_manager: BuiltInManager):
self.symbol_table: symtable = symtable(code, '<string>', 'exec')
self.code: str = code
self.input_vars: List[SymbolWrapper] = CodeObject._find_input_variables(self.symbol_table, ns_manager
)
self.output_vars: FrozenSet[SymbolWrapper] = CodeObject._find_output_variables(self.symbol_table
)
h = blake2b(digest_size=10, key=key)
if len(self.output_vars) > 0:
display_id_prefix = "+".join(map(str, self.output_vars))
h.update(display_id_prefix.encode('utf-8'))
self.display_id = f"{display_id_prefix}-{h.hexdigest()}"
else:
h.update(self.code.encode('utf-8'))
self.display_id = f"{h.hexdigest()}"
示例4: ss58_encode
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import blake2b [as 别名]
def ss58_encode(address, address_type=42):
checksum_prefix = b'SS58PRE'
if type(address) is bytes or type(address) is bytearray:
address_bytes = address
else:
address_bytes = bytes.fromhex(address)
if len(address_bytes) == 32:
# Checksum size is 2 bytes for public key
checksum_length = 2
elif len(address_bytes) in [1, 2, 4, 8]:
# Checksum size is 1 byte for account index
checksum_length = 1
else:
raise ValueError("Invalid length for address")
address_format = bytes([address_type]) + address_bytes
checksum = blake2b(checksum_prefix + address_format).digest()
return base58.b58encode(address_format + checksum[:checksum_length]).decode()
示例5: create_from_account_list
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import blake2b [as 别名]
def create_from_account_list(cls, accounts, threshold):
from scalecodec.utils.ss58 import ss58_decode
account_ids = []
for account in accounts:
if account[0:2] != '0x':
account = '0x{}'.format(ss58_decode(account))
account_ids.append(account)
account_list_cls = cls.get_decoder_class('Vec<AccountId>')
account_list_data = account_list_cls.encode(sorted(account_ids))
threshold_data = cls.get_decoder_class("u16").encode(threshold)
multi_account_id = "0x{}".format(blake2b(
b"modlpy/utilisuba" + bytes(account_list_data.data) + bytes(threshold_data.data), digest_size=32
).digest().hex())
multi_account_obj = cls()
multi_account_obj.encode(multi_account_id)
return multi_account_obj
示例6: make_key
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import blake2b [as 别名]
def make_key(self, key: Union[str, handlers.HandlerId], max_length: int = 63) -> str:
# K8s has a limitation on the allowed charsets in annotation/label keys.
# https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/#syntax-and-character-set
safe_key = key.replace('/', '.')
# K8s has a limitation of 63 chars per annotation/label key.
# Force it to 63 chars by replacing the tail with a consistent hash (with full alphabet).
# Force it to end with alnums instead of altchars or trailing chars (K8s requirement).
prefix = f'{self.prefix}/' if self.prefix else ''
if len(safe_key) <= max_length - len(prefix):
suffix = ''
else:
digest = hashlib.blake2b(safe_key.encode('utf-8'), digest_size=4).digest()
alnums = base64.b64encode(digest, altchars=b'-.').decode('ascii')
suffix = f'-{alnums}'.rstrip('=-.')
full_key = f'{prefix}{safe_key[:max_length - len(prefix) - len(suffix)]}{suffix}'
return full_key
示例7: __init__
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import blake2b [as 别名]
def __init__(self, pw=None):
"""
Args:
pw (byte-like): A password that deterministically generates the key.
"""
super().__init__()
if not pw:
self.key = None
self.keyParams = None
return
# If a password was provided, create a new set of key parameters and an
# authentication code.
salt = rando.newKey()
_, hashName, iterations = defaultKDFParams()
b = ByteArray(
hashlib.pbkdf2_hmac(hashName, bytes(pw), salt.bytes(), iterations)
)
self.key = b[:32]
self.keyParams = KDFParams(salt)
authKey = b[32:].bytes()
authMsg = self.keyParams.baseParams().bytes()
self.keyParams.auth = ByteArray(
hashlib.blake2b(authMsg, digest_size=32, key=authKey).digest()
)
示例8: blake2bchecksum
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import blake2b [as 别名]
def blake2bchecksum(file_path):
"""
Calculates hash of the file
Parameters
----------
file_path : str
path to the file
"""
with open(file_path, 'rb') as fh:
m = hashlib.blake2b()
while True:
data = fh.read(8192)
if not data:
break
m.update(data)
return m.hexdigest()
示例9: sign
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import blake2b [as 别名]
def sign(self, key):
'''Sign this transaction with a private key.
A potentially already existing signature would be overridden.
'''
h = blake2b(digest_size=32)
h.update(rlp.encode(self, ThorTransaction.exclude(["Signature"])))
rawhash = h.digest()
if key in (0, "", b"\x00" * 32, "0" * 64):
raise Exception("Zero privkey cannot sign")
if len(key) == 64:
key = to_bytes(hexstr=key) # we need a binary key
pk = keys.PrivateKey(key)
self.Signature = pk.sign_msg_hash(rawhash).to_bytes()
#
# estimate eth gas
#
示例10: blake
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import blake2b [as 别名]
def blake(x):
return blake2b(x).digest()[:32]
示例11: hash
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import blake2b [as 别名]
def hash(x):
return blake2b(x).digest()[:32]
示例12: hash
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import blake2b [as 别名]
def hash(self) -> str:
""" Returns the Blake2b hash of the view """
b2b = hashlib.blake2b()
with open(self._path, "rb") as f:
for chunk in iter(lambda: f.read(8192), b""):
b2b.update(chunk)
return b2b.hexdigest()
示例13: get_name
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import blake2b [as 别名]
def get_name( s ):
full_name = s.get_full_name()
if len(full_name) < 64:
return full_name
param_hash = blake2b(digest_size = 8)
param_hash.update(s.get_field_str().encode('ascii'))
return f'{s.cls.__name__}__{param_hash.hexdigest()}'
# def get_file_info( s ):
# return s.file_info
示例14: get_component_unique_name
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import blake2b [as 别名]
def get_component_unique_name( c_rtype ):
full_name = get_component_full_name( c_rtype )
special_chars = [' ', '<', '>', '.']
if len( full_name ) < 64 and not any([c in full_name for c in special_chars]):
return full_name
comp_name = c_rtype.get_name()
param_hash = blake2b(digest_size = 8)
param_hash.update(full_name[len(comp_name):].encode('ascii'))
param_name = param_hash.hexdigest()
return comp_name + "__" + param_name
示例15: get_file_hash
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import blake2b [as 别名]
def get_file_hash( file_path ):
with open(file_path) as fd:
hash_inst = blake2b()
string = ''.join( fd.readlines() ).encode( 'ascii' )
hash_inst.update(string)
return hash_inst.hexdigest()