Python sha3.sha3_256() Examples

The following are 30 code examples of sha3.sha3_256(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sha3 , or try the search function .
Example #1
Source File: test_transaction.py    From Decentralized-Internet with MIT License 6 votes vote down vote up
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) 
Example #2
Source File: utils.py    From indy-plenum with Apache License 2.0 6 votes vote down vote up
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 
Example #3
Source File: test_offchain.py    From bigchaindb-driver with Apache License 2.0 6 votes vote down vote up
def test_fulfill_transaction(alice_transaction, alice_sk):
    from bigchaindb_driver.offchain import fulfill_transaction
    fulfilled_transaction = fulfill_transaction(
        alice_transaction, private_keys=alice_sk)
    inputs = fulfilled_transaction['inputs']
    assert len(inputs) == 1
    alice_transaction['inputs'][0]['fulfillment'] = None
    message = rapidjson.dumps(
        alice_transaction,
        skipkeys=False,
        ensure_ascii=False,
        sort_keys=True,
    )
    message = sha3_256(message.encode())
    fulfillment_uri = inputs[0]['fulfillment']
    assert Fulfillment.from_uri(fulfillment_uri).\
        validate(message=message.digest()) 
Example #4
Source File: test_transaction.py    From bigchaindb with Apache License 2.0 6 votes vote down vote up
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) 
Example #5
Source File: tendermint_utils.py    From Decentralized-Internet with MIT License 5 votes vote down vote up
def merkleroot(hashes):
    """Computes the merkle root for a given list.

    Args:
        hashes (:obj:`list` of :obj:`bytes`): The leaves of the tree.

    Returns:
        str: Merkle root in hexadecimal form.

    """
    # XXX TEMPORARY -- MUST REVIEW and possibly CHANGE
    # The idea here is that the UTXO SET would be empty and this function
    # would be invoked to compute the merkle root, and since there is nothing,
    # i.e. an empty list, then the hash of the empty string is returned.
    # This seems too easy but maybe that is good enough? TO REVIEW!
    if not hashes:
        return sha3_256(b'').hexdigest()
    # XXX END TEMPORARY -- MUST REVIEW ...
    if len(hashes) == 1:
        return hexlify(hashes[0]).decode()
    if len(hashes) % 2 == 1:
        hashes.append(hashes[-1])
    parent_hashes = [
        sha3_256(hashes[i] + hashes[i+1]).digest()
        for i in range(0, len(hashes)-1, 2)
    ]
    return merkleroot(parent_hashes) 
Example #6
Source File: tendermint_utils.py    From Decentralized-Internet with MIT License 5 votes vote down vote up
def calculate_hash(key_list):
    if not key_list:
        return ''

    full_hash = sha3_256()
    for key in key_list:
        full_hash.update(key.encode('utf8'))

    return full_hash.hexdigest() 
Example #7
Source File: tendermint_utils.py    From Decentralized-Internet with MIT License 5 votes vote down vote up
def merkleroot(hashes):
    """Computes the merkle root for a given list.

    Args:
        hashes (:obj:`list` of :obj:`bytes`): The leaves of the tree.

    Returns:
        str: Merkle root in hexadecimal form.

    """
    # XXX TEMPORARY -- MUST REVIEW and possibly CHANGE
    # The idea here is that the UTXO SET would be empty and this function
    # would be invoked to compute the merkle root, and since there is nothing,
    # i.e. an empty list, then the hash of the empty string is returned.
    # This seems too easy but maybe that is good enough? TO REVIEW!
    if not hashes:
        return sha3_256(b'').hexdigest()
    # XXX END TEMPORARY -- MUST REVIEW ...
    if len(hashes) == 1:
        return hexlify(hashes[0]).decode()
    if len(hashes) % 2 == 1:
        hashes.append(hashes[-1])
    parent_hashes = [
        sha3_256(hashes[i] + hashes[i+1]).digest()
        for i in range(0, len(hashes)-1, 2)
    ]
    return merkleroot(parent_hashes) 
Example #8
Source File: transaction.py    From Decentralized-Internet with MIT License 5 votes vote down vote up
def _sign_simple_signature_fulfillment(cls, input_, message, key_pairs):
        """Signs a Ed25519Fulfillment.

            Args:
                input_ (:class:`~bigchaindb.common.transaction.
                    Input`) The input to be signed.
                message (str): The message to be signed
                key_pairs (dict): The keys to sign the Transaction with.
        """
        # NOTE: To eliminate the dangers of accidentally signing a condition by
        #       reference, we remove the reference of input_ here
        #       intentionally. If the user of this class knows how to use it,
        #       this should never happen, but then again, never say never.
        input_ = deepcopy(input_)
        public_key = input_.owners_before[0]
        message = sha3_256(message.encode())
        if input_.fulfills:
            message.update('{}{}'.format(
                input_.fulfills.txid, input_.fulfills.output).encode())

        try:
            # cryptoconditions makes no assumptions of the encoding of the
            # message to sign or verify. It only accepts bytestrings
            input_.fulfillment.sign(
                message.digest(), base58.b58decode(key_pairs[public_key].encode()))
        except KeyError:
            raise KeypairMismatchException('Public key {} is not a pair to '
                                           'any of the private keys'
                                           .format(public_key))
        return input_ 
Example #9
Source File: test_transaction_structure.py    From Decentralized-Internet with MIT License 5 votes vote down vote up
def test_tx_serialization_hash_function(signed_create_tx):
    tx = signed_create_tx.to_dict()
    tx['id'] = None
    payload = json.dumps(tx, skipkeys=False, sort_keys=True,
                         separators=(',', ':'))
    assert sha3.sha3_256(payload.encode()).hexdigest() == signed_create_tx.id 
Example #10
Source File: test_transaction_structure.py    From Decentralized-Internet with MIT License 5 votes vote down vote up
def test_create_tx_no_asset_data(b, create_tx, alice):
    tx_body = create_tx.to_dict()
    del tx_body['asset']['data']
    tx_serialized = json.dumps(
        tx_body, skipkeys=False, sort_keys=True, separators=(',', ':'))
    tx_body['id'] = sha3.sha3_256(tx_serialized.encode()).hexdigest()
    validate_raises(tx_body)


################################################################################
# Inputs 
Example #11
Source File: test_transactions.py    From Decentralized-Internet with MIT License 5 votes vote down vote up
def test_post_create_transaction_with_invalid_signature(mock_logger,
                                                        b,
                                                        client):
    from bigchaindb.common.exceptions import InvalidSignature
    from bigchaindb.models import Transaction
    user_priv, user_pub = crypto.generate_key_pair()

    tx = Transaction.create([user_pub], [([user_pub], 1)]).to_dict()
    tx['inputs'][0]['fulfillment'] = 64 * '0'
    tx['id'] = sha3_256(
        json.dumps(
            tx,
            sort_keys=True,
            separators=(',', ':'),
            ensure_ascii=False,
        ).encode(),
    ).hexdigest()

    res = client.post(TX_ENDPOINT, data=json.dumps(tx))
    expected_status_code = 400
    expected_error_message = (
        'Invalid transaction ({}): Fulfillment URI '
        'couldn\'t been parsed'
    ).format(InvalidSignature.__name__)
    assert res.status_code == expected_status_code
    assert res.json['message'] == expected_error_message
    assert mock_logger.error.called
    assert (
        'HTTP API error: %(status)s - %(method)s:%(path)s - %(message)s' in
        mock_logger.error.call_args[0]
    )
    assert (
        {
            'message': expected_error_message, 'status': expected_status_code,
            'method': 'POST', 'path': TX_ENDPOINT
        } in mock_logger.error.call_args[0]
    )
    # TODO put back caplog based asserts once possible
    # assert caplog.records[0].args['status'] == expected_status_code
    # assert caplog.records[0].args['message'] == expected_error_message 
Example #12
Source File: test_transaction.py    From Decentralized-Internet with MIT License 5 votes vote down vote up
def test_validate_tx_threshold_duplicated_pk(user_pub, user_priv,
                                             asset_definition):
    from cryptoconditions import Ed25519Sha256, ThresholdSha256
    from bigchaindb.common.transaction import Input, Output, Transaction

    threshold = ThresholdSha256(threshold=2)
    threshold.add_subfulfillment(
        Ed25519Sha256(public_key=b58decode(user_pub)))
    threshold.add_subfulfillment(
        Ed25519Sha256(public_key=b58decode(user_pub)))

    threshold_input = Input(threshold, [user_pub, user_pub])
    threshold_output = Output(threshold, [user_pub, user_pub])

    tx = Transaction(Transaction.CREATE, asset_definition,
                     [threshold_input], [threshold_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 = deepcopy(threshold_input)
    expected.fulfillment.subconditions[0]['body'].sign(
        message, b58decode(user_priv))
    expected.fulfillment.subconditions[1]['body'].sign(
        message, b58decode(user_priv))

    tx.sign([user_priv, user_priv])

    subconditions = tx.inputs[0].fulfillment.subconditions
    expected_subconditions = expected.fulfillment.subconditions
    assert subconditions[0]['body'].to_dict()['signature'] == \
        expected_subconditions[0]['body'].to_dict()['signature']
    assert subconditions[1]['body'].to_dict()['signature'] == \
        expected_subconditions[1]['body'].to_dict()['signature']

    assert tx.inputs[0].to_dict()['fulfillment'] == \
        expected.fulfillment.serialize_uri()
    assert tx.inputs_valid() is True 
Example #13
Source File: test_transaction.py    From Decentralized-Internet with MIT License 5 votes vote down vote up
def test_transaction_hash(fulfilled_transaction):
    from bigchaindb.common.transaction import Transaction
    tx_obj = Transaction.from_dict(fulfilled_transaction)
    assert tx_obj._id is None
    assert tx_obj.id is None
    thing_to_hash = json.dumps(fulfilled_transaction, sort_keys=True,
                               separators=(',', ':'), ensure_ascii=True)
    expected_hash_id = sha3_256(thing_to_hash.encode()).hexdigest()
    tx_obj._hash()
    assert tx_obj._id == expected_hash_id
    assert tx_obj.id == expected_hash_id 
Example #14
Source File: test_lib.py    From Decentralized-Internet with MIT License 5 votes vote down vote up
def test_get_utxoset_merkle_root_when_no_utxo(b):
    assert b.get_utxoset_merkle_root() == sha3_256(b'').hexdigest() 
Example #15
Source File: test_utils.py    From Decentralized-Internet with MIT License 5 votes vote down vote up
def test_merkleroot():
    from bigchaindb.tendermint_utils import merkleroot
    hashes = [sha3_256(i.encode()).digest() for i in 'abc']
    assert merkleroot(hashes) == (
        '78c7c394d3158c218916b7ae0ebdea502e0f4e85c08e3b371e3dfd824d389fa3') 
Example #16
Source File: key_factory.py    From libra-client with MIT License 5 votes vote down vote up
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 
Example #17
Source File: transaction.py    From Decentralized-Internet with MIT License 5 votes vote down vote up
def _sign_simple_signature_fulfillment(cls, input_, message, key_pairs):
        """Signs a Ed25519Fulfillment.

            Args:
                input_ (:class:`~bigchaindb.common.transaction.
                    Input`) The input to be signed.
                message (str): The message to be signed
                key_pairs (dict): The keys to sign the Transaction with.
        """
        # NOTE: To eliminate the dangers of accidentally signing a condition by
        #       reference, we remove the reference of input_ here
        #       intentionally. If the user of this class knows how to use it,
        #       this should never happen, but then again, never say never.
        input_ = deepcopy(input_)
        public_key = input_.owners_before[0]
        message = sha3_256(message.encode())
        if input_.fulfills:
            message.update('{}{}'.format(
                input_.fulfills.txid, input_.fulfills.output).encode())

        try:
            # cryptoconditions makes no assumptions of the encoding of the
            # message to sign or verify. It only accepts bytestrings
            input_.fulfillment.sign(
                message.digest(), base58.b58decode(key_pairs[public_key].encode()))
        except KeyError:
            raise KeypairMismatchException('Public key {} is not a pair to '
                                           'any of the private keys'
                                           .format(public_key))
        return input_ 
Example #18
Source File: crypto.py    From Decentralized-Internet with MIT License 5 votes vote down vote up
def hash_data(data):
    """Hash the provided data using SHA3-256"""
    return sha3_256(data.encode()).hexdigest() 
Example #19
Source File: conftest.py    From bigchaindb-driver with Apache License 2.0 5 votes vote down vote up
def hash_transaction(transaction):
    return sha3_256(serialize_transaction(transaction).encode()).hexdigest() 
Example #20
Source File: conftest.py    From bigchaindb-driver with Apache License 2.0 5 votes vote down vote up
def sign_transaction(transaction, *, public_key, private_key):
    ed25519 = Ed25519Sha256(public_key=base58.b58decode(public_key))
    message = json.dumps(
        transaction,
        sort_keys=True,
        separators=(',', ':'),
        ensure_ascii=False,
    )
    message = sha3_256(message.encode())
    ed25519.sign(message.digest(), base58.b58decode(private_key))
    return ed25519.serialize_uri() 
Example #21
Source File: transaction.py    From bigchaindb-driver with Apache License 2.0 5 votes vote down vote up
def _sign_simple_signature_fulfillment(cls, input_, message, key_pairs):
        """Signs a Ed25519Fulfillment.

            Args:
                input_ (:class:`~bigchaindb.common.transaction.
                    Input`) The input to be signed.
                message (str): The message to be signed
                key_pairs (dict): The keys to sign the Transaction with.
        """
        # NOTE: To eliminate the dangers of accidentally signing a condition by
        #       reference, we remove the reference of input_ here
        #       intentionally. If the user of this class knows how to use it,
        #       this should never happen, but then again, never say never.
        input_ = deepcopy(input_)
        public_key = input_.owners_before[0]
        message = sha3_256(message.encode())
        if input_.fulfills:
            message.update('{}{}'.format(
                input_.fulfills.txid, input_.fulfills.output).encode())

        try:
            # cryptoconditions makes no assumptions of the encoding of the
            # message to sign or verify. It only accepts bytestrings
            input_.fulfillment.sign(
                message.digest(),
                base58.b58decode(key_pairs[public_key].encode()))
        except KeyError:
            raise KeypairMismatchException('Public key {} is not a pair to '
                                           'any of the private keys'
                                           .format(public_key))
        return input_ 
Example #22
Source File: crypto.py    From bigchaindb-driver with Apache License 2.0 5 votes vote down vote up
def hash_data(data):
    """Hash the provided data using SHA3-256"""
    return sha3.sha3_256(data.encode()).hexdigest() 
Example #23
Source File: func.py    From openNAMU with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def pw_encode(data, data2 = '', type_d = ''):
    if type_d == '':
        curs.execute(db_change('select data from other where name = "encode"'))
        set_data = curs.fetchall()

        type_d = set_data[0][0]

    if type_d == 'sha256':
        return hashlib.sha256(bytes(data, 'utf-8')).hexdigest()
    else:
        if sys.version_info < (3, 6):
            return sha3.sha3_256(bytes(data, 'utf-8')).hexdigest()
        else:
            return hashlib.sha3_256(bytes(data, 'utf-8')).hexdigest() 
Example #24
Source File: client.py    From pylibra with MIT License 5 votes vote down vote up
def send_transaction(
        self,
        sender,
        transaction,
        max_gas_amount=10000,
        gas_unit_price=0,
        expiration_time=None,
    ):
        account_state = self.get_account_state(sender.address)

        seq = 0
        if account_state:
            seq = account_state.sequence_number

        if expiration_time is None:
            expiration_time = int(time.time()) + 10

        raw_tx = transaction.as_raw_transaction(
            sender.address, seq, max_gas_amount, gas_unit_price, expiration_time
        )
        raw_txn_bytes = raw_tx.SerializeToString()

        shazer = sha3_256()
        shazer.update(
            bytes.fromhex(
                "46f174df6ca8de5ad29745f91584bb913e7df8dd162e3e921a5c1d8637c88d16"
            )
        )
        shazer.update(raw_txn_bytes)

        request = SubmitTransactionRequest()
        signed_txn = request.signed_txn
        signed_txn.sender_public_key = bytes.fromhex(sender.public_key)
        signed_txn.raw_txn_bytes = raw_txn_bytes
        signed_txn.sender_signature = sender.sign(shazer.digest())[:64]
        return self.stub.SubmitTransaction(request) 
Example #25
Source File: __init__.py    From pylibra with MIT License 5 votes vote down vote up
def get_account(self, counter):
        shazer = sha3_256()
        shazer.update(self.entropy)
        shazer.update(counter.to_bytes(32, "big"))
        return Account(shazer.digest().hex()) 
Example #26
Source File: account.py    From pylibra with MIT License 5 votes vote down vote up
def __init__(self, private_key):
        self._signing_key = SigningKey(bytes.fromhex(private_key))
        self._verify_key = self._signing_key.verify_key
        shazer = sha3_256()
        shazer.update(self._verify_key.encode())
        self.address = shazer.digest().hex() 
Example #27
Source File: test_transaction_structure.py    From bigchaindb with Apache License 2.0 5 votes vote down vote up
def test_tx_serialization_hash_function(signed_create_tx):
    tx = signed_create_tx.to_dict()
    tx['id'] = None
    payload = json.dumps(tx, skipkeys=False, sort_keys=True,
                         separators=(',', ':'))
    assert sha3.sha3_256(payload.encode()).hexdigest() == signed_create_tx.id 
Example #28
Source File: key_factory.py    From libra-client with MIT License 5 votes vote down vote up
def has_sha3():
    return 'sha3_256' in hashlib.algorithms_available 
Example #29
Source File: ethash_utils.py    From pyquarkchain with MIT License 5 votes vote down vote up
def _sha3_256(x):
        return _sha3.sha3_256(x).digest() 
Example #30
Source File: ethash.py    From pyquarkchain with MIT License 5 votes vote down vote up
def sha3_256(x):
    return hash_words(lambda v: sha3.sha3_256(v).digest(), 32, x)