ethereum.crypto

Cryptographic Functions

..contents:: Table of Contents
backlinks

none

local

Introduction

Cryptographic primatives used in—but not defined by—the Ethereum specification.

Module Contents

Functions

keccak256

Computes the keccak256 hash of the input buffer.

keccak512

Computes the keccak512 hash of the input buffer.

secp256k1_recover

Recovers the public key from a given signature.

Module Details

keccak256

ethereum.crypto.keccak256(buffer: ethereum.base_types.Bytes)ethereum.eth_types.Hash32

Computes the keccak256 hash of the input buffer.

Parameters

buffer – Input for the hashing function.

Returns

hash – Output of the hash function.

Return type

eth1spec.eth_types.Hash32

def keccak256(buffer: Bytes) -> Hash32:
    return sha3.keccak_256(buffer).digest()

keccak512

ethereum.crypto.keccak512(buffer: ethereum.base_types.Bytes)ethereum.eth_types.Hash64

Computes the keccak512 hash of the input buffer.

Parameters

buffer – Input for the hashing function.

Returns

hash – Output of the hash function.

Return type

eth1spec.eth_types.Hash32

def keccak512(buffer: Bytes) -> Hash64:
    return sha3.keccak_512(buffer).digest()

secp256k1_recover

ethereum.crypto.secp256k1_recover(r: ethereum.base_types.U256, s: ethereum.base_types.U256, v: ethereum.base_types.U256, msg_hash: ethereum.eth_types.Hash32)ethereum.base_types.Bytes

Recovers the public key from a given signature.

Parameters
  • r – TODO

  • s – TODO

  • v – TODO

  • msg_hash – Hash of the message being recovered.

Returns

public_key – Recovered public key.

Return type

eth1spec.base_types.Bytes

def secp256k1_recover(r: U256, s: U256, v: U256, msg_hash: Hash32) -> Bytes:
    r_bytes = r.to_be_bytes32()
    s_bytes = s.to_be_bytes32()

    signature = bytearray([0] * 65)
    signature[32 - len(r_bytes) : 32] = r_bytes
    signature[64 - len(s_bytes) : 64] = s_bytes
    signature[64] = v
    public_key = coincurve.PublicKey.from_signature_and_message(
        bytes(signature), msg_hash, hasher=None
    )
    public_key = public_key.format(compressed=False)[1:]
    return public_key