Python sha3.keccak_256() Examples

The following are 30 code examples of sha3.keccak_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: address.py    From monero-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def with_payment_id(self, payment_id=0):
        """Integrates payment id into the address.

        :param payment_id: int, hexadecimal string or :class:`PaymentID <monero.numbers.PaymentID>`
                    (max 64-bit long)

        :rtype: `IntegratedAddress`
        :raises: `TypeError` if the payment id is too long
        """
        payment_id = numbers.PaymentID(payment_id)
        if not payment_id.is_short():
            raise TypeError("Payment ID {0} has more than 64 bits and cannot be integrated".format(payment_id))
        prefix = const.INTADDRR_NETBYTES[const.NETS.index(self.net)]
        data = bytearray([prefix]) + self._decoded[1:65] + struct.pack('>Q', int(payment_id))
        checksum = bytearray(keccak_256(data).digest()[:4])
        return IntegratedAddress(base58.encode(hexlify(data + checksum))) 
Example #2
Source File: btcrseed.py    From btcrecover with GNU General Public License v2.0 6 votes vote down vote up
def _addresses_to_hash160s(addresses):
        hash160s = set()
        for address in addresses:
            if address[:2].lower() == "0x":
                address = address[2:]
            if len(address) != 40:
                raise ValueError("length (excluding any '0x' prefix) of Ethereum addresses must be 40")
            cur_hash160 = base64.b16decode(address, casefold=True)
            if not address.islower():  # verify the EIP55 checksum unless all letters are lowercase
                checksum = sha3.keccak_256(base64.b16encode(cur_hash160).lower()).digest()
                for nibble, c in enumerate(address, 0):
                    if c.isalpha() and \
                       c.isupper() != bool(ord(checksum[nibble // 2]) & (0b1000 if nibble&1 else 0b10000000)):
                            raise ValueError("invalid EIP55 checksum")
            hash160s.add(cur_hash160)
        return hash160s 
Example #3
Source File: evm.py    From manticore with GNU Affero General Public License v3.0 6 votes vote down vote up
def symbolic_function(self, func, data):
        """
        Get an unsound symbolication for function `func`

        """
        data = self.try_simplify_to_constant(data)
        try:
            result = []
            self._publish(
                "on_symbolic_function", func, data, result
            )  # This updates the local copy of result

            return result[0]
        except Exception as e:
            logger.info("Error! %r", e)
            data_c = SelectedSolver.instance().get_value(self.constraints, data)
            return int(sha3.keccak_256(data_c).hexdigest(), 16) 
Example #4
Source File: seed.py    From monero-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def public_address(self, net=const.NET_MAIN):
        """Returns the master :class:`Address <monero.address.Address>` represented by the seed.

        :param net: the network, one of `const.NET_*`; default is `const.NET_MAIN`

        :rtype: :class:`Address <monero.address.Address>`
        """
        # backward compatibility
        _net = net[:-3] if net.endswith('net') else net
        if _net != net:
            warnings.warn(
                "Argument '{:s}' is deprecated and will not be accepted in 0.8, "
                "use one of monero.const.NET_*".format(net),
                DeprecationWarning)
            net = _net
        if net not in const.NETS:
            raise ValueError(
                "Invalid net argument '{:s}'. Must be one of monero.const.NET_*".format(net))
        netbyte = (18, 53, 24)[const.NETS.index(net)]
        data = "{:x}{:s}{:s}".format(netbyte, self.public_spend_key(), self.public_view_key())
        h = keccak_256()
        h.update(unhexlify(data))
        checksum = h.hexdigest()
        return address(base58.encode(data + checksum[0:8])) 
Example #5
Source File: evm.py    From manticore with GNU Affero General Public License v3.0 6 votes vote down vote up
def calculate_new_address(sender=None, nonce=None):
        if sender is None:
            # Just choose a random address for regular accounts:
            new_address = random.randint(100, pow(2, 160))
        elif issymbolic(sender):
            # TODO(Evan Sultanik): In the interim before we come up with a better solution,
            #                      consider breaking Yellow Paper comability and just returning
            #                      a random contract address here
            raise EthereumError(
                "Manticore does not yet support contracts with symbolic addresses creating new contracts"
            )
        else:
            if nonce is None:
                # assume that the sender is a contract account, which is initialized with a nonce of 1
                nonce = 1
            new_address = int(sha3.keccak_256(rlp.encode([sender, nonce])).hexdigest()[24:], 16)
        return new_address 
Example #6
Source File: __init__.py    From minter-sdk with MIT License 6 votes vote down vote up
def keccak_hash(data, digest_bits=256):
        """
        Create Keccak hash.
        Args:
            data (bytes)
            digest_bits (int)
        Returns:
            hex (string)
        """

        if digest_bits == 256:
            khash = sha3.keccak_256()
        else:
            raise NotImplementedError

        khash.update(data)

        return khash.hexdigest() 
Example #7
Source File: coinlector.py    From RansomCoinPublic with Apache License 2.0 6 votes vote down vote up
def xmr_verify( xmr_match ):
    try:
        pubAddrHex = monero.base58.decode(xmr_match.decode("utf8"))
        pubAddrChksum = pubAddrHex[-8:]
        pubAddrForHash = pubAddrHex[:-8]
        #print(pubAddrChksum)
        #print(pubAddrForHash)
        k = sha3.keccak_256()
        k.update(unhexlify(pubAddrForHash))
        pubAddrHash = k.hexdigest()
        pubAddrChksum2 = pubAddrHash[:8]
        if pubAddrChksum2 == pubAddrChksum:
            #print("True: %s" % xmr_match)
            return True
        else:
            #print("False: %s" % xmr_match)
            return False
    except Exception as E:
        #print("Exception: %s" % E)
        return False

# Section for regexes of interest as Indicators of Compromise

# URLs 
Example #8
Source File: evm.py    From manticore with GNU Affero General Public License v3.0 5 votes vote down vote up
def globalsha3(data):
    if issymbolic(data):
        return None
    return int(sha3.keccak_256(data).hexdigest(), 16) 
Example #9
Source File: address.py    From monero-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _decode(self, address):
        self._decoded = bytearray(unhexlify(base58.decode(address)))
        checksum = self._decoded[-4:]
        if checksum != keccak_256(self._decoded[:-4]).digest()[:4]:
            raise ValueError("Invalid checksum in address {}".format(address))
        if self._decoded[0] not in self._valid_netbytes:
            raise ValueError("Invalid address netbyte {nb}. Allowed values are: {allowed}".format(
                nb=self._decoded[0],
                allowed=", ".join(map(lambda b: '%02x' % b, self._valid_netbytes)))) 
Example #10
Source File: evm.py    From manticore with GNU Affero General Public License v3.0 5 votes vote down vote up
def block_hash(self, block_number=None, force_recent=True):
        """
        Calculates a block's hash

        :param block_number: the block number for which to calculate the hash, defaulting to the most recent block
        :param force_recent: if True (the default) return zero for any block that is in the future or older than 256 blocks
        :return: the block hash
        """
        if block_number is None:
            block_number = self.block_number() - 1

        # We are not maintaining an actual -block-chain- so we just generate
        # some hashes for each virtual block
        value = sha3.keccak_256((repr(block_number) + "NONCE").encode()).hexdigest()
        value = int(value, 16)

        if force_recent:
            # 0 is left on the stack if the looked for block number is greater or equal
            # than the current block number or more than 256 blocks behind the current
            # block. (Current block hash is unknown from inside the tx)
            bnmax = Operators.ITEBV(256, self.block_number() > 256, 256, self.block_number())
            value = Operators.ITEBV(
                256,
                Operators.OR(block_number >= self.block_number(), block_number < bnmax),
                0,
                value,
            )

        return value 
Example #11
Source File: utils.py    From teether with Apache License 2.0 5 votes vote down vote up
def sha3(data):
    return keccak_256(data).digest() 
Example #12
Source File: rpc.py    From eth-testrpc with MIT License 5 votes vote down vote up
def web3_sha3(self, value, encoding='hex'):
        logger.info('web3_sha3')
        if encoding == 'hex':
            value = decode_hex(value)
        else:
            value = force_bytes(value)
        return encode_32bytes(keccak_256(value).digest()) 
Example #13
Source File: auth.py    From trinity with MIT License 5 votes vote down vote up
def handshake(
        remote: NodeAPI,
        privkey: datatypes.PrivateKey,
        ) -> Tuple[bytes, bytes, sha3.keccak_256, sha3.keccak_256, asyncio.StreamReader, asyncio.StreamWriter]:  # noqa: E501
    """
    Perform the auth handshake with given remote.

    Returns the established secrets and the StreamReader/StreamWriter pair already connected to
    the remote.
    """
    use_eip8 = False
    initiator = HandshakeInitiator(remote, privkey, use_eip8)
    reader, writer = await initiator.connect()
    try:
        aes_secret, mac_secret, egress_mac, ingress_mac = await _handshake(
            initiator, reader, writer)
    except BaseException:
        # Note: This is one of two places where we manually handle closing the
        # reader/writer connection pair in the event of an error during the
        # peer connection and handshake process.
        # See `p2p.peer.handshake` for the other.
        if not reader.at_eof():
            reader.feed_eof()
        writer.close()
        await asyncio.sleep(0)
        raise

    return aes_secret, mac_secret, egress_mac, ingress_mac, reader, writer 
Example #14
Source File: auth.py    From trinity with MIT License 5 votes vote down vote up
def _handshake(initiator: 'HandshakeInitiator', reader: asyncio.StreamReader,
                     writer: asyncio.StreamWriter,
                     ) -> Tuple[bytes, bytes, sha3.keccak_256, sha3.keccak_256]:
    """See the handshake() function above.

    This code was factored out into this helper so that we can create Peers with directly
    connected readers/writers for our tests.
    """
    initiator_nonce = keccak(os.urandom(HASH_LEN))
    auth_msg = initiator.create_auth_message(initiator_nonce)
    auth_init = initiator.encrypt_auth_message(auth_msg)

    if writer.transport.is_closing():
        raise HandshakeFailure("Error during handshake with {initiator.remote!r}. Writer closed.")

    writer.write(auth_init)

    auth_ack = await asyncio.wait_for(reader.read(ENCRYPTED_AUTH_ACK_LEN), timeout=REPLY_TIMEOUT)

    if reader.at_eof():
        # This is what happens when Parity nodes have blacklisted us
        # (https://github.com/ethereum/py-evm/issues/901).
        raise HandshakeFailure(f"{initiator.remote!r} disconnected before sending auth ack")

    ephemeral_pubkey, responder_nonce = initiator.decode_auth_ack_message(auth_ack)
    aes_secret, mac_secret, egress_mac, ingress_mac = initiator.derive_secrets(
        initiator_nonce,
        responder_nonce,
        ephemeral_pubkey,
        auth_init,
        auth_ack
    )

    return aes_secret, mac_secret, egress_mac, ingress_mac 
Example #15
Source File: auth.py    From trinity with MIT License 5 votes vote down vote up
def derive_secrets(self,
                       initiator_nonce: bytes,
                       responder_nonce: bytes,
                       remote_ephemeral_pubkey: datatypes.PublicKey,
                       auth_init_ciphertext: bytes,
                       auth_ack_ciphertext: bytes
                       ) -> Tuple[bytes, bytes, sha3.keccak_256, sha3.keccak_256]:
        """Derive base secrets from ephemeral key agreement."""
        # ecdhe-shared-secret = ecdh.agree(ephemeral-privkey, remote-ephemeral-pubk)
        ecdhe_shared_secret = ecies.ecdh_agree(
            self.ephemeral_privkey, remote_ephemeral_pubkey)

        # shared-secret = keccak(ecdhe-shared-secret || keccak(nonce || initiator-nonce))
        shared_secret = keccak(
            ecdhe_shared_secret + keccak(responder_nonce + initiator_nonce))

        # aes-secret = keccak(ecdhe-shared-secret || shared-secret)
        aes_secret = keccak(ecdhe_shared_secret + shared_secret)

        # mac-secret = keccak(ecdhe-shared-secret || aes-secret)
        mac_secret = keccak(ecdhe_shared_secret + aes_secret)

        # setup keccak instances for the MACs
        # egress-mac = sha3.keccak_256(mac-secret ^ recipient-nonce || auth-sent-init)
        mac1 = sha3.keccak_256(
            sxor(mac_secret, responder_nonce) + auth_init_ciphertext
        )
        # ingress-mac = sha3.keccak_256(mac-secret ^ initiator-nonce || auth-recvd-ack)
        mac2 = sha3.keccak_256(
            sxor(mac_secret, initiator_nonce) + auth_ack_ciphertext
        )

        if self._is_initiator:
            egress_mac, ingress_mac = mac1, mac2
        else:
            egress_mac, ingress_mac = mac2, mac1

        return aes_secret, mac_secret, egress_mac, ingress_mac 
Example #16
Source File: transport.py    From trinity with MIT License 5 votes vote down vote up
def __init__(self,
                 remote: NodeAPI,
                 private_key: datatypes.PrivateKey,
                 reader: asyncio.StreamReader,
                 writer: asyncio.StreamWriter,
                 aes_secret: bytes,
                 mac_secret: bytes,
                 egress_mac: sha3.keccak_256,
                 ingress_mac: sha3.keccak_256) -> None:
        self.remote = remote
        self.session = Session(self.remote)

        self._private_key = private_key

        # Encryption and Cryptography *stuff*
        self._egress_mac = egress_mac
        self._ingress_mac = ingress_mac

        self._reader = reader
        self._writer = writer

        # FIXME: Insecure Encryption: https://github.com/ethereum/devp2p/issues/32
        iv = b"\x00" * 16
        aes_secret = aes_secret
        mac_secret = mac_secret

        aes_cipher = Cipher(algorithms.AES(aes_secret), modes.CTR(iv), default_backend())
        self._aes_enc = aes_cipher.encryptor()
        self._aes_dec = aes_cipher.decryptor()

        mac_cipher = Cipher(algorithms.AES(mac_secret), modes.ECB(), default_backend())
        self._mac_enc = mac_cipher.encryptor().update 
Example #17
Source File: random_oracles.py    From pyUmbral with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, customization_string: bytes = b''):
        self._upper = sha3.keccak_256()
        self._lower = sha3.keccak_256()

        self._upper.update(self._UPPER_PREFIX)
        self._lower.update(self._LOWER_PREFIX)

        super().__init__(customization_string) 
Example #18
Source File: abi.py    From manticore with GNU Affero General Public License v3.0 5 votes vote down vote up
def function_selector(method_name_and_signature):
        """
        Makes a function hash id from a method signature
        """
        s = sha3.keccak_256()
        s.update(method_name_and_signature.encode())
        return bytes(s.digest()[:4]) 
Example #19
Source File: btcrseed.py    From btcrecover with GNU General Public License v2.0 5 votes vote down vote up
def pubkey_to_hash160(uncompressed_pubkey):
        """convert from an uncompressed public key to its Ethereum hash160 form

        :param uncompressed_pubkey: SEC 1 EllipticCurvePoint OctetString
        :type uncompressed_pubkey: str
        :return: last 20 bytes of keccak256(raw_64_byte_pubkey)
        :rtype: str
        """
        assert len(uncompressed_pubkey) == 65 and uncompressed_pubkey[0] == "\x04"
        return sha3.keccak_256(uncompressed_pubkey[1:]).digest()[-20:]


################################### Main ################################### 
Example #20
Source File: utils.py    From ilf with Apache License 2.0 5 votes vote down vote up
def sha3_256(x): return _sha3.keccak_256(x).digest() 
Example #21
Source File: cryptonote.py    From MoneroPy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def keccak_256(s):
    #return Keccak().Keccak((len(s)*4, s), 1088, 512, 0x01, 32*8, False).lower()
    k = sha3.keccak_256()
    k.update(s)
    return k.hexdigest() 
Example #22
Source File: cryptonote.py    From MoneroPy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def cn_fast_hash(s):
    return keccak_256(unhexlify(s)) 
Example #23
Source File: function.py    From slither with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_function_id(sig):
    ''''
        Return the function id of the given signature
    Args:
        sig (str)
    Return:
        (int)
    '''
    s = sha3.keccak_256()
    s.update(sig.encode('utf-8'))
    return int("0x" + s.hexdigest()[:8], 16) 
Example #24
Source File: utils.py    From blocksim with MIT License 5 votes vote down vote up
def keccak_256(value):
        return _sha3.keccak_256(value).digest() 
Example #25
Source File: utils.py    From blocksim with MIT License 5 votes vote down vote up
def keccak_256(value):
        return keccak.new(digest_bits=256, data=value).digest() 
Example #26
Source File: ecdsa.py    From solcrypto with GNU General Public License v3.0 5 votes vote down vote up
def pubkey_to_ethaddr(pubkey):
	if isinstance(pubkey, tuple):
		assert len(pubkey) == 2
		pubkey = b.encode_pubkey(pubkey, 'bin')
	return hexlify(keccak_256(pubkey[1:]).digest()[12:]) 
Example #27
Source File: utils.py    From solcrypto with GNU General Public License v3.0 5 votes vote down vote up
def hashs(*x):
    data = b''.join(map(tobe256, x))
    return bytes_to_int(keccak_256(data).digest()) 
Example #28
Source File: seed.py    From monero-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _hex_seed_keccak(self):
        h = keccak_256()
        h.update(unhexlify(self.hex))
        return h.digest() 
Example #29
Source File: address.py    From monero-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def base_address(self):
        """Returns the base address without payment id.
        :rtype: :class:`Address`
        """
        prefix = const.MASTERADDR_NETBYTES[const.NETS.index(self.net)]
        data = bytearray([prefix]) + self._decoded[1:65]
        checksum = keccak_256(data).digest()[:4]
        return Address(base58.encode(hexlify(data + checksum))) 
Example #30
Source File: wallet.py    From monero-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_address(self, major, minor):
        """
        Calculates sub-address for account index (`major`) and address index within
        the account (`minor`).

        :rtype: :class:`BaseAddress <monero.address.BaseAddress>`
        """
        # ensure indexes are within uint32
        if major < 0 or major >= 2**32:
            raise ValueError('major index {} is outside uint32 range'.format(major))
        if minor < 0 or minor >= 2**32:
            raise ValueError('minor index {} is outside uint32 range'.format(minor))
        master_address = self.address()
        if major == minor == 0:
            return master_address
        master_svk = unhexlify(self.view_key())
        master_psk = unhexlify(self.address().spend_key())
        # m = Hs("SubAddr\0" || master_svk || major || minor)
        hsdata = b''.join([
                b'SubAddr\0', master_svk,
                struct.pack('<I', major), struct.pack('<I', minor)])
        m = keccak_256(hsdata).digest()
        # D = master_psk + m * B
        D = ed25519.edwards_add(
                ed25519.decodepoint(master_psk),
                ed25519.scalarmult_B(ed25519.decodeint(m)))
        # C = master_svk * D
        C = ed25519.scalarmult(D, ed25519.decodeint(master_svk))
        netbyte = bytearray([const.SUBADDR_NETBYTES[const.NETS.index(master_address.net)]])
        data = netbyte + ed25519.encodepoint(D) + ed25519.encodepoint(C)
        checksum = keccak_256(data).digest()[:4]
        return address.SubAddress(base58.encode(hexlify(data + checksum)))