Keccak-256 Hash Generator

Compute Ethereum Keccak-256 cryptographic hashes for smart contracts, Solidity function selectors, and EVM addresses.

4.9 / 5· 148 verified ratings
•
100% Client-Side Privacy
•
Verified 2026 Engine
Loading tool engine...
Frequently Used With:Base64 Encoder & Decoder →MD5 Hash Generator →JWT Decoder →HMAC Signature Generator →
Institutional-Grade Accuracy & Client-Side Privacy Guarantee

Unlike conventional calculator sites that send your financial numbers, payload data, or code snippets across remote web servers, Affi-Chain processes all mathematical derivations, algorithms, and data parsing 100% locally within your browser sandbox. No tracking cookies, no server-side retention, and zero transmission lag.

Cryptographic Foundations & The Keccak Permutation

Keccak-256 is the cryptographic hashing algorithm that forms the foundational security layer of the Ethereum Virtual Machine (EVM), Web3 smart contracts, Merkle Patricia Tries, and decentralized digital signatures. Designed by Guido Bertoni, Joan Daemen, Michaël Peeters, and Gilles Van Assche, Keccak won the prestigious five-year National Institute of Standards and Technology (NIST) hash algorithm competition in October 2012 to become the official next-generation SHA-3 standard.

+---------------------------------------------------------------------------------------------------+
|                                  THE KECCAK-256 SPONGE CONSTRUCTION                              |
+---------------------------------------------------------------------------------------------------+
|  ABSORBING PHASE (Bitwise XOR into State)                 SQUEEZING PHASE (State Extraction)      |
|  Message Blocks: M0, M1, M2...                            Extract 256-Bit Cryptographic Digest    |
|       |                                                               |                           |
|      (XOR) <--- Rate Bits (r = 1088 bits)                             v                           |
|  [ 1600-Bit State Matrix ]  === 24 Rounds of f[1600] ===> [ 256-Bit Keccak Digest ]              |
|  [ Capacity: c = 512 bits]  (θ, ρ, π, χ, ι Permutations)   (0x5c0754... Ethereum Hash)            |
+---------------------------------------------------------------------------------------------------+

The Sponge Construction Architecture

Unlike legacy hash families (MD5, SHA-1, and SHA-2) that employ the Davies-Meyer / Merkle-Damgård iterative compression framework, Keccak introduces the Sponge Construction:

  1. The 1600-Bit State Matrix: The internal state is structured as a $5 \times 5$ array of 64-bit words ($5 \times 5 \times 64 = 1600$ bits).
  2. Rate ($r$) and Capacity ($c$): The 1600-bit state is partitioned into two regions: the Rate ($r = 1088$ bits) and the Capacity ($c = 512$ bits), satisfying $r + c = 1600$. Security against generic collision and preimage attacks depends entirely on capacity $c$, providing $c/2 = 256$ bits of cryptographic collision resistance.
  3. The 24 Rounds of Keccak-$f[1600]$: For every block absorbed, the state matrix undergoes 24 rounds of five algebraic step mappings:
    • $\theta$ (Theta): Column parity mixing and diffusion.
    • $\rho$ (Rho): Bitwise bit rotation within each 64-bit word.
    • $\pi$ (Pi): Fixed transposition permutation of words within the matrix.
    • $\chi$ (Chi): Non-linear row mapping providing cryptographic confusion (the only non-linear transformation in Keccak).
    • $\iota$ (Iota): Asymmetric round constant XOR injection to eliminate symmetry between rounds.

Keccak-256 vs. NIST SHA-3-256 Padding Divergence

A crucial point of confusion in modern software engineering is the subtle but profound divergence between Ethereum Keccak-256 and Official NIST SHA-3-256 (FIPS PUB 202):

+---------------------------------------------------------------------------------------------------+
|                              PADDING DOMAIN SEPARATION DIVERGENCE                                 |
+---------------------------------------------------------------------------------------------------+
|  Specification                  Standard Suffix / Delimiter Byte   Hex Digest of "" (Empty String)|
|  -----------------------------  ---------------------------------  -----------------------------  |
|  Ethereum Keccak-256            0x01 (Single padding bit)          c5d2460186f7233c927e7db2dcc7...|
|  Official NIST SHA-3-256        0x06 (Domain separation 0b0110)    a7ffc6f8bf1ed76651c14756a061...|
+---------------------------------------------------------------------------------------------------+

When Ethereum co-founder Vitalik Buterin and the core developers implemented the Ethereum protocol in 2014, they adopted the original Keccak specification as published by its authors. In August 2015, when NIST finalized FIPS 202, they altered the domain separation padding byte to 0x06 to distinguish SHA-3 from internal SHAKE extendable output functions.

Because changing Ethereum's core hashing function post-launch would have broken every existing wallet address, signature, and deployed smart contract, Ethereum permanently retains the original Keccak-256 specification. Standard SHA-3 libraries from generic cryptographic toolkits will produce invalid signatures and addresses if used on EVM networks.


Production Code Implementation

Python: Web3 Keccak-256, Function Selector & Address Synthesis

#!/usr/bin/env python3
"""
Production Keccak-256 Web3 Engine:
Synthesizes EVM Function Selectors, Computes Ethereum Addresses from Raw Public Keys,
and Demonstrates EIP-712 Structured Data Hashing.
"""

from typing import Tuple
import hashlib

# Check for native eth_hash / sha3 module or fallback to pure python Keccak
try:
    from eth_hash.auto import keccak as eth_keccak
except ImportError:
    # Use hashlib's internal shake/sha3 with custom padding or pycryptodome fallback
    from Crypto.Hash import keccak as pycrypto_keccak

    def eth_keccak(data: bytes) -> bytes:
        k = pycrypto_keccak.new(digest_bits=256)
        k.update(data)
        return k.digest()


class EthereumKeccakTool:
    @staticmethod
    def hash(payload: bytes) -> bytes:
        """Computes canonical Ethereum Keccak-256 digest."""
        return eth_keccak(payload)

    @classmethod
    def compute_function_selector(cls, method_signature: str) -> str:
        """
        Calculates the 4-byte ABI function selector used in EVM transactions.
        Example: 'transfer(address,uint256)' -> '0xa9059cbb'
        """
        digest = cls.hash(method_signature.encode("utf-8"))
        selector_4bytes = digest[:4]
        return "0x" + selector_4bytes.hex()

    @classmethod
    def public_key_to_address(cls, uncompressed_pubkey_bytes: bytes) -> str:
        """
        Derives a 20-byte Ethereum checksum address from a 64-byte uncompressed SECP256k1 public key.
        Formula: Last 20 bytes of keccak256(pubkey_uncompressed).
        """
        if len(uncompressed_pubkey_bytes) == 65 and uncompressed_pubkey_bytes[0] == 0x04:
            # Strip 0x04 uncompressed prefix byte
            uncompressed_pubkey_bytes = uncompressed_pubkey_bytes[1:]

        if len(uncompressed_pubkey_bytes) != 64:
            raise ValueError("Expected 64 bytes of uncompressed public key coordinates (X, Y).")

        digest = cls.hash(uncompressed_pubkey_bytes)
        raw_address_bytes = digest[-20:]
        raw_address_hex = raw_address_bytes.hex()

        # EIP-55 Mixed-Case Checksum Encoding
        return cls.to_checksum_address(raw_address_hex)

    @classmethod
    def to_checksum_address(cls, address_hex: str) -> str:
        """Applies EIP-55 checksum encoding to prevent typographical errors."""
        clean_addr = address_hex.lower().replace("0x", "")
        hash_digest = cls.hash(clean_addr.encode("utf-8")).hex()

        checksummed = ["0x"]
        for i, ch in enumerate(clean_addr):
            if ch in "0123456789":
                checksummed.append(ch)
            else:
                # If the i-th hex digit of hash >= 8, uppercase; otherwise lowercase
                if int(hash_digest[i], 16) >= 8:
                    checksummed.append(ch.upper())
                else:
                    checksummed.append(ch.lower())

        return "".join(checksummed)


# Demonstration
if __name__ == "__main__":
    tool = EthereumKeccakTool()

    # 1. Hashing Basic Message
    msg = b"Hello, Ethereum World!"
    digest_hex = tool.hash(msg).hex()
    print("--- ETHEREUM KECCAK-256 HASH ---")
    print(f"Message: {msg.decode('utf-8')}")
    print(f"Keccak-256 Digest: 0x{digest_hex}")

    # 2. Function Selectors
    fn_sig = "transfer(address,uint256)"
    selector = tool.compute_function_selector(fn_sig)
    print(f"\nFunction Signature: {fn_sig}")
    print(f"4-Byte Selector:    {selector}")

    # 3. Known Public Key to Address Verification
    # Dummy uncompressed public key (64 bytes = 128 hex chars)
    dummy_pub = bytes.fromhex(
        "50863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b2352"
        "2cd470243453a299fa9e77237716103abc11a1df38855ed6f2ee187e9c582ba6"
    )
    derived_addr = tool.public_key_to_address(dummy_pub)
    print(f"\nDerived EIP-55 Address: {derived_addr}")

TypeScript: Microservice Engine using @noble/hashes

/**
 * Modern TypeScript Keccak-256 implementation using @noble/hashes
 * Fully compatible with EVM execution without heavy web3 dependencies.
 */

import { keccak_256 } from "@noble/hashes/sha3";
import { bytesToHex, utf8ToBytes } from "@noble/hashes/utils";

export class Web3KeccakService {
  /**
   * Computes Keccak-256 hash returned as a 0x-prefixed hex string
   */
  public static hashHex(input: string | Uint8Array): string {
    const bytes = typeof input === "string" ? utf8ToBytes(input) : input;
    const digest = keccak_256(bytes);
    return `0x${bytesToHex(digest)}`;
  }

  /**
   * Extracts the 4-byte ERC-20/EVM function selector
   */
  public static getSelector(signature: string): string {
    const cleanSig = signature.replace(/\s+/g, ""); // Remove spaces
    const hash = this.hashHex(cleanSig);
    return hash.slice(0, 10); // '0x' + 8 hex chars = 4 bytes
  }

  /**
   * Encodes a standard ERC-20 transfer calldata payload
   */
  public static encodeTransfer(recipientAddress: string, amountWei: bigint): string {
    const selector = this.getSelector("transfer(address,uint256)");
    const cleanAddress = recipientAddress.toLowerCase().replace("0x", "").padStart(64, "0");
    const cleanAmount = amountWei.toString(16).padStart(64, "0");
    return `${selector}${cleanAddress}${cleanAmount}`;
  }
}

Cryptographic Hash Algorithms Comparison Matrix

AlgorithmState/Block Size (Bits)Security MarginEVM Gas CostPrimary Deployment ArenaZK-Circuit Friendliness
Keccak-2561600 (Sponge)256 bits30 gas + 6/wordEthereum Protocol, Solidity ABI, Merkle TriesLow (High R1CS constraint count)
NIST SHA-3-2561600 (Sponge)256 bitsNot Supported nativelyStandardized Federal Systems (FIPS 202)Low
SHA-256512 (Merkle-Damgård)128 bits (against length ext.)60 gas + 12/word (Precompile)Bitcoin Protocol, TLS/SSL, Git CommitsLow
BLAKE3512 (Tree Hash)128 bitsHigh in EVM (No opcode)High-throughput distributed storage (IPFS)Low
Poseidon / RescueCustom Prime Field128 bitsHigh in raw EVM, Cheap in ZKZero-Knowledge Proofs (zk-SNARKs / zk-Rollups)Ultra High (~10x to 100x fewer gates)

Critical Ethereum & Web3 Edge Cases

1. The Catastrophic ABI Packing Hash Collision (abi.encodePacked)

In Solidity, developers frequently compute digests using keccak256(abi.encodePacked(a, b)) to save gas.

  • Unlike abi.encode (which pads each parameter to 32 bytes), abi.encodePacked concatenates variable-length arguments without delimiter padding.
  • The Vulnerability: $$\text{abi.encodePacked}("\text{hello}", "\text{world}") \implies \text{"helloworld"}$$ $$\text{abi.encodePacked}("\text{hell}", "\text{oworld}") \implies \text{"helloworld"}$$
  • Both distinct parameter sets produce identical byte arrays, resulting in identical Keccak-256 hashes. In authentication routines or cryptographic signature verifications, this allows an attacker to forge authorized inputs.
  • Remediation: Always use abi.encode when hashing dynamic variables (strings or byte arrays), or enforce explicit length delimiters.

2. 4-Byte Function Selector Collisions

EVM transactions invoke contract methods using only the first 4 bytes (32 bits) of keccak256("methodSignature").

  • A 32-bit namespace contains only $2^{32} \approx 4.29 \times 10^9$ possibilities.
  • Under the Birthday Paradox, finding a collision between two function signatures requires computing approximately $\sqrt{2^{32}} \approx 65,536$ hashes.
  • Attackers have engineered benign-looking function signatures that collide with sensitive governance methods (e.g., executeTransaction(...)), tricking multi-signature wallets or security audits into executing malicious logic.

3. Signature Malleability in ecrecover

In ECDSA signatures over Keccak-256 digests ($v, r, s$):

  • For any valid signature $(r, s)$, the tuple $(r, -s \bmod n)$ is also mathematically valid over the SECP256k1 curve.
  • Attackers who observe an in-flight transaction can flip the $s$ value to create a valid, alternative signature that computes the same signer address. If a smart contract relies on the raw signature hash to prevent double-spending or replay attacks, the alternate signature bypasses deduplication checks.
  • Remediation: Enforce OpenZeppelin's ECDSA library, which enforces lower-half $s$ bounds ($s \le n/2$) per EIP-2.

Frequently Asked Questions

How does Keccak-256 differ from standard NIST SHA-3?
Ethereum adopted Keccak-256 before NIST finalized SHA-3. They share the same sponge permutation core but use slightly different padding bytes (0x01 vs 0x06).

Explore Related Utilities