本文整理汇总了Python中hashlib.sha3_256方法的典型用法代码示例。如果您正苦于以下问题:Python hashlib.sha3_256方法的具体用法?Python hashlib.sha3_256怎么用?Python hashlib.sha3_256使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类hashlib
的用法示例。
在下文中一共展示了hashlib.sha3_256方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: hash
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import sha3_256 [as 别名]
def hash(proto_with_payload):
"""
Calculates hash of payload of proto message
:proto_with_payload: proto transaction or query
:return: bytes representation of hash
"""
obj = None
if hasattr(proto_with_payload, 'payload'):
obj = getattr(proto_with_payload, 'payload')
# hash of meta is implemented for block streaming queries,
# because they do not have a payload in their schema
elif hasattr(proto_with_payload, 'meta'):
obj = getattr(proto_with_payload, 'meta')
bytes = obj.SerializeToString()
hash = hashlib.sha3_256(bytes).digest()
return hash
示例2: _layer_cipher
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import sha3_256 [as 别名]
def _layer_cipher(constant: bytes, revision_counter: int, subcredential: bytes, blinded_key: bytes, salt: bytes) -> Tuple['cryptography.hazmat.primitives.ciphers.Cipher', Callable[[bytes], bytes]]: # type: ignore
try:
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
except ImportError:
raise ImportError('Layer encryption/decryption requires the cryptography module')
kdf = hashlib.shake_256(blinded_key + subcredential + struct.pack('>Q', revision_counter) + salt + constant)
keys = kdf.digest(S_KEY_LEN + S_IV_LEN + MAC_LEN)
secret_key = keys[:S_KEY_LEN]
secret_iv = keys[S_KEY_LEN:S_KEY_LEN + S_IV_LEN]
mac_key = keys[S_KEY_LEN + S_IV_LEN:]
cipher = Cipher(algorithms.AES(secret_key), modes.CTR(secret_iv), default_backend())
mac_prefix = struct.pack('>Q', len(mac_key)) + mac_key + struct.pack('>Q', len(salt)) + salt
return cipher, lambda ciphertext: hashlib.sha3_256(mac_prefix + ciphertext).digest()
示例3: address_from_identity_key
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import sha3_256 [as 别名]
def address_from_identity_key(key: Union[bytes, 'cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PublicKey', 'cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey'], suffix: bool = True) -> str: # type: ignore
"""
Converts a hidden service identity key into its address. This accepts all
key formats (private, public, or public bytes).
:param key: hidden service identity key
:param suffix: includes the '.onion' suffix if true, excluded otherwise
:returns: **str** hidden service address
:raises: **ImportError** if key is a cryptographic type and ed25519 support
is unavailable
"""
key = stem.util._pubkey_bytes(key) # normalize key into bytes
version = stem.client.datatype.Size.CHAR.pack(3)
checksum = hashlib.sha3_256(CHECKSUM_CONSTANT + key + version).digest()[:2]
onion_address = base64.b32encode(key + checksum + version)
return stem.util.str_tools._to_unicode(onion_address + b'.onion' if suffix else onion_address).lower()
示例4: sha3
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import sha3_256 [as 别名]
def sha3(seed):
return sha3_256(to_string(seed))
# assert encode_hex(sha3(b'')) == b'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470'
#def normalize_address(x, allow_blank=False):
# if is_numeric(x):
# return int_to_addr(x)
# if allow_blank and x in {'', b''}:
# return b''
# if len(x) in (42, 50) and x[:2] in {'0x', b'0x'}:
# x = x[2:]
# if len(x) in (40, 48):
# x = decode_hex(x)
# if len(x) == 24:
# assert len(x) == 24 and sha3(x[:20])[:4] == x[-4:]
# x = x[:20]
# if len(x) != 20:
# raise Exception("Invalid address format: %r" % x)
# return x
示例5: sign
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import sha3_256 [as 别名]
def sign(self, data, is_hash: bool):
if is_hash:
if isinstance(data, str):
try:
data = data.split("0x")[1] if data.startswith("0x") else data
data = binascii.unhexlify(data)
except Exception as e:
logging.error(f"hash data must hex string or bytes \n exception : {e}")
return None
if not isinstance(data, (bytes, bytearray)):
logging.error(f"data must be bytes \n")
return None
raw_sig = self.private_key.ecdsa_sign_recoverable(msg=data,
raw=is_hash,
digest=hashlib.sha3_256)
serialized_sig, recover_id = self.private_key.ecdsa_recoverable_serialize(raw_sig)
return serialized_sig + bytes((recover_id, ))
示例6: to_hash32
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import sha3_256 [as 别名]
def to_hash32(self, value: Union[Hash32, bytes, bytearray, int, bool, dict]):
if value is None:
return Hash32.empty()
elif isinstance(value, Hash32):
return value
elif isinstance(value, (bytes, bytearray)) and len(value) == 32:
return Hash32(value)
if isinstance(value, bool):
value = b'\x01' if value else b'\x00'
elif isinstance(value, int):
if value < 0:
raise RuntimeError(f"value : {value} is negative.")
value = value.to_bytes((value.bit_length() + 7) // 8, "big")
elif isinstance(value, dict):
if self.type == BlockProverType.Receipt:
value = dict(value)
value.pop("failure", None)
value.pop("blockHash", None)
hash_generator = self.get_hash_generator()
value = hash_generator.generate_salted_origin(value)
value = value.encode()
return Hash32(hashlib.sha3_256(value).digest())
示例7: _sign
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import sha3_256 [as 别名]
def _sign(self,
private_key: typing.Optional[PrivateKey] = None,
signature: typing.Optional[bytes] = None) -> None:
"""
Add a signature to this data.
Supply either your private key for signing or pass an existing signature.
:param private_key: the private key to sign with.
:param signature: the signature to adapt.
"""
if private_key is not None and signature is None:
self.signature = private_key.signature(self.get_plaintext())
elif private_key is None and signature is not None:
self.signature = signature
else:
raise RuntimeError("Specify either private_key or signature!")
self._hash = hashlib.sha3_256(self.get_plaintext_signed()).digest()
示例8: __init__
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import sha3_256 [as 别名]
def __init__(self, public_key: Optional[PublicKey] = None, private_key: Optional[PrivateKey] = None) -> None:
"""
Create a new view of another's chain by specifying a public key or create your own chain by supplying
a private key.
:param public_key: the public key of the owner of this chain.
:param private_key: the private key to use to add tokens to this chain.
"""
super(TokenTree, self).__init__()
self._logger = logging.getLogger(self.__class__.__name__)
self.elements = {}
self.unchained = OrderedDict()
self.unchained_max_size = 100
if public_key is not None and private_key is None:
self.public_key = public_key.pub()
self.private_key = None
elif public_key is None and private_key is not None:
self.private_key = private_key
self.public_key = private_key.pub()
else:
raise RuntimeError("Specify either public_key or private_key!")
self.genesis_hash = sha3_256(self.public_key.key_to_bin()).digest()
示例9: __init__
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import sha3_256 [as 别名]
def __init__(self, info, additional_fields=None, markdown_root='', standard_format=True):
if additional_fields is None:
additional_fields = {}
# Allow info to be a string to simplify the API
if isinstance(info, str):
info = [info]
self._data = OrderedDict()
self._data['elements'] = []
self._data['description'] = ''.join(_convert_to_description(d) for d in info)
self._data['markdown'] = ''.join(_convert_to_markdown(d, markdown_root) for d in info)
id_txt = ''.join(_convert_to_id(d) for d in info)
self._data['id'] = hashlib.sha3_256(id_txt.encode('utf-8')).hexdigest()
if standard_format:
to_add = [i for i in info if not isinstance(i, str)]
for add in to_add:
self.add(add)
if additional_fields:
self._data['additional_fields'] = additional_fields
示例10: test_validate_tx_simple_create_signature
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import sha3_256 [as 别名]
def test_validate_tx_simple_create_signature(user_input, user_output, user_priv,
asset_definition):
from bigchaindb.common.transaction import Transaction
from .utils import validate_transaction_model
tx = Transaction(Transaction.CREATE, asset_definition, [user_input], [user_output])
expected = deepcopy(user_output)
tx_dict = tx.to_dict()
tx_dict['inputs'][0]['fulfillment'] = None
serialized_tx = json.dumps(tx_dict, sort_keys=True,
separators=(',', ':'), ensure_ascii=True)
message = sha3_256(serialized_tx.encode()).digest()
expected.fulfillment.sign(message, b58decode(user_priv))
tx.sign([user_priv])
assert tx.inputs[0].to_dict()['fulfillment'] == \
expected.fulfillment.serialize_uri()
assert tx.inputs_valid() is True
validate_transaction_model(tx)
示例11: has_sha3
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import sha3_256 [as 别名]
def has_sha3():
return 'sha3_256' in hashlib.algorithms_available
示例12: sha3_256_mod
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import sha3_256 [as 别名]
def sha3_256_mod():
if has_sha3():
return hashlib.sha3_256
else:
try:
import sha3
except ModuleNotFoundError:
cmd = "python3 -m pip install --user pysha3"
print("try to install pysha3 with following command:")
print(cmd)
subprocess.run(cmd.split(), check=True)
import sha3
return sha3.sha3_256
示例13: reduced_hash
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import sha3_256 [as 别名]
def reduced_hash(transaction):
"""
Calculates hash of reduced payload of a transaction
:param transaction: transaction to be processed
:return: hex representation of hash
"""
bytes = transaction.payload.reduced_payload.SerializeToString()
hash = hashlib.sha3_256(bytes).digest()
hex_hash = binascii.hexlify(hash)
return hex_hash
示例14: identity_key_from_address
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import sha3_256 [as 别名]
def identity_key_from_address(onion_address: str) -> bytes:
"""
Converts a hidden service address into its public identity key.
:param onion_address: hidden service address
:returns: **bytes** for the hidden service's public identity key
:raises: **ValueError** if address malformed or checksum is invalid
"""
if onion_address.endswith('.onion'):
onion_address = onion_address[:-6]
if not stem.util.tor_tools.is_valid_hidden_service_address(onion_address, version = 3):
raise ValueError("'%s.onion' isn't a valid hidden service v3 address" % onion_address)
# onion_address = base32(PUBKEY | CHECKSUM | VERSION) + '.onion'
# CHECKSUM = H('.onion checksum' | PUBKEY | VERSION)[:2]
decoded_address = base64.b32decode(onion_address.upper())
pubkey = decoded_address[:32]
expected_checksum = decoded_address[32:34]
version = decoded_address[34:35]
checksum = hashlib.sha3_256(CHECKSUM_CONSTANT + pubkey + version).digest()[:2]
if expected_checksum != checksum:
checksum_str = stem.util.str_tools._to_unicode(binascii.hexlify(checksum))
expected_checksum_str = stem.util.str_tools._to_unicode(binascii.hexlify(expected_checksum))
raise ValueError('Bad checksum (expected %s but was %s)' % (expected_checksum_str, checksum_str))
return pubkey
示例15: _subcredential
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import sha3_256 [as 别名]
def _subcredential(identity_key: 'cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey', blinded_key: bytes) -> bytes: # type: ignore
# credential = H('credential' | public-identity-key)
# subcredential = H('subcredential' | credential | blinded-public-key)
credential = hashlib.sha3_256(b'credential%s' % stem.util._pubkey_bytes(identity_key)).digest()
return hashlib.sha3_256(b'subcredential%s%s' % (credential, blinded_key)).digest()