Arbitrum Stylus logo

Stylus by Example

Hashing with keccak256

Keccak256 is a cryptographic hash function that takes input of arbitrary length and produces a fixed-length 256-bit output. It is a member of the SHA-3 family.

keccak256 computes the Keccak-256 hash of the input.

Common uses:

  • Deterministic IDs from structured inputs
  • Commit–reveal schemes
  • Compact signatures (sign the hash instead of large inputs)

In Stylus, use stylus_sdk::crypto::keccak to compute the hash:

1pub fn keccak<T: AsRef<[u8]>>(bytes: T) -> B256
1pub fn keccak<T: AsRef<[u8]>>(bytes: T) -> B256

Encoding before hashing

The example below demonstrates hashing ABI-encoded tuples using alloy_sol_types:

  • Standard encoding (padded words) via abi_encode_sequence, then keccak(...)
  • Packed encoding (no padding) via abi_encode_packed, then keccak(...)
  • A manual packed variant by concatenating byte slices
  • Building calldata by hashing a function signature to a 4-byte selector and appending encoded params

Note: Standard decode routines expect padded ABI encoding. Don’t attempt to decode bytes produced by packed encoding.

Full Example code:

src/lib.rs

1Loading...
1Loading...

Cargo.toml

1Loading...
1Loading...

src/main.rs

1Loading...
1Loading...