This C++ library implements a heavyweight
permutation function using AES CPU instructions, plus a duplex/sponge, parallel tree hashing, a keyed MAC, and a PRNG on top.
Heavyweight
describes the design, a wide 256-byte state and a hardware AES round function, not the speed. The tree hashes are fast on page-cache-hot files, where cch beats multithreaded b3sum and castella comes within about 20% of its speed.
Status. Castella is a personal research project, a permutation and hash design that has not been standardized, externally reviewed, or cryptanalyzed by anyone but its author. Do not use it where security matters. See SPEC.md and its security claims and non-claims.
The Castella permutation function operates on a state array of N blocks, where N ∈ {2, 4, 8, 16} and each block is 16 bytes fitting in a SIMD register (e.g., x86-64 XMM, ARM NEON). It uses AES hardware instructions and matrix transpositions to achieve full diffusion of the state array.
Each round of the permutation does the following:
- Perform 3 rounds of AES encryption on each element of the state array, where each element in each AES round uses a distinct round constant as its AES round key.
- The number of AES rounds was empirically determined. See aes_enc_0-aes_num_rounds.cpp.
- Transpose the state, treating it as a 16×16 matrix of bytes.
The minimum number of permutation rounds was empirically determined. See permute-num_rounds.cpp.
The round constants are the successive states of a 128-bit Galois LFSR with the GCM reduction polynomial (x¹²⁸ + x⁷ + x² + x + 1), stepped 128 times between constants. The LFSR seed, which is also the first round constant, is expand 16-byte c
.
The round constants are used as AES round keys. A distinct round constant is used for every combination of permutation round, AES round, and state block, so no two blocks ever apply the same transformation. The generator is deliberately unrelated to the AES round function so that the round constants share no structure with it.
The round constants are generated at compile time. Their number is Castella::NUM_ROUNDS_MAX × Castella::AES_NUM_ROUNDS × Castella::B_MAX, which is 16 × 3 × 16 = 768. All three values are fixed by SPEC.md, and any other value produces different digests.
The Castella duplex class implements a customizable duplex/sponge construction inspired by Keccak (which won the SHA-3 competition). It is byte-oriented (i.e., all input, output, and padding are in whole bytes), unlike SHA-3, which is bit-oriented.
An instance of a duplex can be used as a hash object or a pseudo-random number generator (PRNG).
The source code is liberally annotated with excerpts from the design and development of Keccak. Refer to it for details.
SPEC.md is a standalone specification of the permutation, round constants, duplex, tree mode, MAC construction, and Compress-Castella, readable without the C++. Its completeness is demonstrated by research/spec-conformance.py, an independent pure-Python implementation written from the specification alone that reproduces every digest in tests/KAT.txt.
SPEC.md also states the security claims and non-claims: a falsifiable flat sponge claim in the Keccak tradition, the claimed security strengths (matching the SHA-3 levels at equal capacity), the proven mode reductions, and the supporting evidence.
research/VERIFYING-CLAIMS.md maps every claim to the exact commands that reproduce its evidence. CHALLENGES.md publishes reduced-round collision and preimage targets for anyone who wants to attack the design.
The duplex state of B = 16 blocks is partitioned into an inner part (the capacity
) of C blocks and an outer part (the rate
) of R = B-C blocks, where 2 ≤ C ≤ B/2 and C must be even.
The capacity is the security parameter, and the claimed level is 64·C bits, half the capacity of 128·C bits. Paired with a digest size, it reproduces the SHA-3 levels exactly. The castella program picks the capacity from the digest size by the rule that produces this mapping (smallest even C with 16·C ≥ 2n bytes for an n-byte digest):
| digest size | C |
capacity | collision / preimage / 2nd-preimage | matches |
|---|---|---|---|---|
| 28 bytes | 4 | 512 | 112 / 224 / 224 | SHA3-224 (448-bit capacity, so this maps upward) |
| 32 bytes | 4 | 512 | 128 / 256 / 256 | SHA3-256 |
| 48 bytes | 6 | 768 | 192 / 384 / 384 | SHA3-384 |
| 64 bytes | 8 | 1024 | 256 / 512 / 512 | SHA3-512 |
Round counts appear nowhere in that table, because as in SHA-3 they are safety margin rather than a security parameter (see Yes, this is Keccak!). SPEC.md derives these strengths from the claim, states which (C, num_rounds) instances the claim covers, and gives the margin rationale behind the round counts.
An instance of Castella::Duplex takes these parameters:
| type | name | default value | constraint | description |
|---|---|---|---|---|
int |
capacity_blocks |
none | ∈ [Castella::Duplex::C_MIN, Castella::Duplex::C_MAX] |
The size (in blocks) of the capacity |
int |
num_rounds |
none | ∈ [Castella::NUM_ROUNDS_MIN<Castella::Duplex::B>(), Castella::NUM_ROUNDS_MAX] |
The number of rounds to perform in the Castella permutation function. The security claim covers an instance only at Castella::Duplex::get_num_rounds_claimed(capacity_blocks) rounds or more. |
int |
input_suffix |
0 |
∈ [0, 255] | The byte to append to the input buffer before squeezing |
| contiguous byte range | function_name |
empty | none | The function-name byte string |
| contiguous byte range | customization_str |
empty | none | The customization byte string |
A contiguous byte range (contiguous_byte_range) is any contiguous sized range of std::byte or a narrow character type, such as a std::string_view, a std::span<const std::byte>, or a std::vector<uint8_t>.
Input data may be given as a contiguous byte range (the primary interface) or as raw data (a const void*, size_t pair, implemented in terms of the range form) with these member functions:
add- Add the given data to the input buffer.
add_left_encoded- Add the left-encoded length of the given data, followed by the data itself, to the input buffer.
add_right_encoded- Add the given data, followed by its right-encoded length, to the input buffer.
add_left_encoded and add_right_encoded also take a nonnegative integer, which they encode on its own, as left_encode and right_encode do in SP 800-185.
A string literal is an array that includes its terminating null character, so add("abc") absorbs 4 bytes. Pass "abc"sv to absorb only the 3 characters.
When the input buffer is full, it is absorbed (via XOR) into the outer part of the state.
See The sponge and duplex constructions to learn how the sponge and duplex constructions work.
The duplex uses the pad10*1
padding rule.
Input padding bytes are added before every squeeze_bytes or squeeze_to, even if 0 bytes are squeezed.
The padding rule may be explicitly applied via the apply_padding_rule() member function.
The squeeze_bytes member function performs the following:
- Append the input suffix to the input buffer.
- Apply the padding rule.
- Return the first n bytes of the outer state as a
std::vector<std::byte>, where n is an integer in the interval[0, get_rate_size_bytes()].- Typical values of n are 32, 48, or 64.
- The default value of n is
get_capacity_size_bytes() / 2. - An n outside that interval is clamped into it rather than rejected, so a too-large n yields
get_rate_size_bytes()bytes and a negative n yields none. Steps 1 and 2 still happen either way, so any call advances the state. This leniency is a convenience of the C++ API because the specification definessqueeze(n)only for0 ≤ n ≤ 16R.
The squeeze_to member function does the same, but writes into a caller-provided buffer instead of allocating a vector. The size of the buffer takes the place of n, and as a precondition it is no larger than get_rate_size_bytes(). A debug build asserts that. A release build clamps a larger size the same way, and leaves any bytes past get_rate_size_bytes() untouched.
The forget member function erases the outer state, so that a state captured later gives back no output already squeezed. It performs the following:
- Append the input suffix to the input buffer.
- Apply the padding rule.
- Zeroize the outer state.
- Apply the permutation function.
A squeeze erases nothing, and the permutation function is invertible, so without forget a captured state gives back every earlier output, as far as the last secret input. A pseudorandom generator that must protect what it has already handed out calls forget after each squeeze, as the HTTP PRNG service does. Later output is not protected. It follows from the captured state until secret input is added.
A byte-stream hash is inherently sequential, so a single duplex can never use more than one CPU core. The generic tree-hash layer (Castella::HashTree) restores parallelism with a KangarooTwelve-style two-level tree. The input is split into fixed-size chunks, each chunk after the first is hashed to a fixed-size chaining value by an independent leaf node, and the chaining values are absorbed by a final node in chunk order. The digest depends only on the tree geometry, the node parameters, and the input bytes, never on the thread count or on how the input was split across add() calls.
Castella::DuplexTree is the tree instantiated with Castella::Duplex nodes. (The cch hash program uses a second instantiation over a faster non-cryptographic compression node.)
The castella command-line program wraps DuplexTree and adds a keyed MAC mode (--key-file, KMAC's structure at tree scale). The examples/ programs show the higher-level SP 800-185 constructions built directly on a single Duplex, which are cSHAKE-, KMAC-, TupleHash-, and ParallelHash-like functions.
On x86-64 processors with VAES, two execution-level optimizations apply (neither ever affects a digest):
-
Register-resident permutation. The permutation (every supported state size N) runs in a folded representation that stays in N/2 ymm registers for all rounds, where element j holds blocks j and j+N/2, one per 128-bit lane. The generic path instead bounces the state through memory between the AES rounds' 256-bit accesses and the transpose's 128-bit accesses, a pattern that defeats store-to-load forwarding.
For the 16-block state used by
Duplex, the folded path measured ~1.7× faster, and a plain duplex absorbs at ~3.2 GiB/s per core instead of ~1.9 before folding. research/permute_folded-benchmark.cpp measured the speedup, with results in research/README.md. The ~3.2 absorb rate comes directly from research/duplex-throughput-benchmark.cpp. -
Leaf batching. Both tree hashes process adjacent leaf chunks two at a time on one thread.
DuplexTreepacks two duplex states into the two 128-bit lanes of ymm registers (Castella::DuplexX2), where VAES applies an independent AES round per lane and the AVX2 unpack network transposes both 16×16 byte matrices at once without mixing the lanes (Castella::permute_x2). One paired permutation measures ~1.7× faster than two sequential (register-resident) permutations (research/permute_x2-benchmark.cpp).The
cchtree instead interleaves two nodes' compression chains in one loop (compress_castella_hash_x2). A single cch node is latency-bound, so the second state's chains fill the idle AES slots, for a modest ~1.1× on pinned runs. research/simd_compress-num_states-benchmark.cpp measured it, and research/README.md has the findings.Pairing applies on every parallel path: batch workers, the inline path (in a single-threaded tree, for an early small batch, and in
cchat any thread count), and the streaming pipeline. The pipeline's pool workers claim up to two adjacent ring slots per wake-up, and streamedcastella --no-mmapinput at the default 8 rounds is fastest at 3 threads, which is where an automatic thread count stops.
All of these ratios are machine-dependent. To reproduce them, build research/ (see Building) and run bash run-benchmarks.bash there. It pins each benchmark to core 0 and saves the raw results to research/results/. Benchmark on an otherwise idle machine.
On a modern x86-64 Linux system, with VAES leaf batching:
castella, the cryptographicDuplexTree, runs at about 0.8× the speed of fully-multithreadedb3sumon page-cache-hot files at its default 8 rounds, and even single-threaded beats BLAKE2b, SHA-1, and MD5 (the algorithms ofb2sum,sha1sum, andmd5sum).cch, the same tree over faster non-cryptographic nodes, beats fully-multithreadedb3sumby about 2.0× on the same files, and single-threaded beats XXH3 (xxhsum -H3) by about 1.2×.
These comparisons come from hash-programs/benchmark.hash-programs.bash. It uses hyperfine to time castella and cch against b3sum, xxhsum, OpenSSL, and coreutils/uutils cksum on a 500 MiB file, which hyperfine's warm-up runs make page-cache-hot. The results are machine-dependent, so run it yourself.
- GCC 14 or newer
- C++23
- clang++ is not supported
- An x86-64 or ARM64 processor with AES instructions
- x86-64 is the only tested platform
- ARM64 is supported in principle, and no ARM64 build has been checked against tests/KAT.txt
The top-level Makefile recurses into the subdirectories:
-
makebuilds the examples, the hash programs, and the tests. -
make testbuilds and runs every test suite, by delegating to each subdirectory's owntesttarget. The Python steps needpython3.tests/: the fixed tests, the KAT file checker, the randomized equivalence tests, the folded-vs-generic permute comparison, and the differential fuzzerexamples/: the exampleshash-programs/: the correctness scriptresearch/: the spec-conformance model, the trail-model cross-validation, and the invariant-subspace self-test
-
make everythingadditionally buildsresearch/(needs google-benchmark) andhttp-prng-service/(needs spdlog).httplib.his committed in-tree, and the Makefile re-downloads it only if it is missing. -
make BUILD=debugbuilds with ASan and UBSan instead of-O3 -flto=auto, and with the internal assertions enabled (seeconfig.mk).BUILDis a variable rather than a target, so it applies to whatever goals are given, andmake BUILD=debug testandmake BUILD=debug everythingare debug builds throughout. Runmake cleanfirst when switching between release and debug. The two use the same binary names.-
The assertions check internal invariants and are not input validation. They are compiled out of a release build, so no release behavior depends on them. Every user-reachable constraint (the
Duplexconstructor parameters and the hash programs' options) is checked by throwing instead, in every build.The exception is the deliberately unchecked accessors, where an assertion backs a documented narrow contract and a checked counterpart exists:
fixed_vector::operator[]versusat(), andunchecked_emplace_back()andunchecked_push_back()versusemplace_back()andpush_back().
-
-
make test-sanruns every test suite under the sanitizers, doing themake cleanthat switching build types requires. It cleans, buildsBUILD=debug, and runs the suites with UBSan set to fail rather than only report. The sanitizer binaries are left in place afterward, somake cleanagain before building for release. -
make cleanandmake lintrecurse into every subdirectory.
Each subdirectory also has its own Makefile with the same all/clean/lint targets, and the four with tests to run (tests/, examples/, hash-programs/, and research/) add test, so a single one can be worked on in isolation. make -C tests test builds and runs just that directory's suites. (research/'s test runs only its three pure-Python scripts, and so does not build the benchmarks or require google-benchmark.)
In real life, castella is the name of a type of sponge cake. https://en.wikipedia.org/wiki/Castella
I asked ChatGPT to suggest names of food that had the word sponge
in them, or had a sponge-like quality. I narrowed the choices to those based on sponge cake or similar desserts. Coincidentally, a castella cake may be large and rectangular, just like the Castella state array.
It's the deliberate opposite of lightweight cryptography, the family of designs (Ascon and friends) built for constrained devices out of a small state and cheap ARX operations. Castella goes the other way on both axes:
- A large state. 256 bytes! For comparison, the state size of SHA-3 is 200 bytes.
- A hardware round function. It uses dedicated AES instructions instead of only ARX operations.
Heavyweight
describes the design, not the speed. It assumes a CPU with an AES unit and spends it freely, so the tree hashes are fast.
Is this as fast as b3sum?
No! Nothing is as fast as b3sum!
But seriously, in my testing, Castella hash comes within about 20% of fully-multithreaded b3sum on page-cache-hot files, and Compress-Castella hash beats it! Don't take my word for it. Performance has the figures and the script that reproduces them.
Could Castella be considered a cryptographic hash function or a cryptographic primitive?
Not yet. It hasn't been scrutinized by others, and until it has been, the honest answer stays no. What exists now is a precise target for that scrutiny. SPEC.md states a falsifiable security claim with its supporting evidence, and CHALLENGES.md publishes reduced-round collision and preimage challenges. Although I myself can't break it. 1
- That's not a question.
- I didn't
roll
anything. That is, I'm not using this for anything serious, and neither should you.
This project was started to satiate a curiosity about the sponge construction and SHA-3. Sometimes it's fun to build something just to learn how it works.
The capacity (C) determines the rate (R). The size of the input buffer is R blocks and it has an alignment of 1 block (i.e., 16 bytes).
If the unit of the capacity were bytes instead of blocks, the value would have to be a multiple of 16 anyway.
| directory | contents |
|---|---|
include/ |
The Castella library headers (castella-permute.hpp, castella-duplex.hpp, castella-hash-tree.hpp, castella-duplex-tree.hpp, castella-duplex-x2.hpp), the Compress-Castella headers (cch.hpp, cch-tree.hpp, cch-x2.hpp), and supporting headers |
examples/ |
Usage examples: cSHAKE-like, KMAC-like, TupleHash-like, and ParallelHash-like operations |
tests/ |
Correctness tests |
research/ |
Parameter searches, the cryptanalysis evidence behind the security claims (trail search, MILP, and algebraic bounds), the spec-conformance model, and benchmarks |
hash-programs/ |
Command-line hash utilities (castella and cch) |
http-prng-service/ |
HTTP server exposing a Castella-backed PRNG via /absorb and /squeeze endpoints |
Castella is licensed under the Mozilla Public License 2.0 (MPL-2.0), and every source file except the vendored httplib.h carries an SPDX header.
- Cryptographic sponge functions
- Duplexing the sponge: single-pass authenticated encryption and other applications
- FIPS PUB 202 SHA-3 Standard: Permutation-Based Hash and Extendable-Output Functions
- NIST Special Publication 800-185 SHA-3 Derived Functions: cSHAKE, KMAC, TupleHash and ParallelHash
- The sponge and duplex constructions
- Keccak specifications summary
- The making of Keccak
- The Joy Of Duplexes
- A software interface for Keccak
- Glossary
- Strengths of Keccak
- Sponge-based pseudo-random number generators
- SHA-3, Keccak and disturbing implementation stories
- Byte ordering and bit numbering in Keccak and SHA-3
- SHAKE, cSHAKE and some more bit ordering
- SHAKE and SP 800-185
- The Design of Rijndael
- The Design Of Rijndael – Errata
- permutation function
- AES
- matrix transpose/transposition
- bit diffusion
- duplex
- sponge
- customizable
- hash
- PRNG
- Keccak
- SHA-3
- XOF
- SHAKE
- cSHAKE
- KMAC
- TupleHash
Footnotes
-
Schneier's Law
Anyone, from the most clueless amateur to the best cryptographer, can create an algorithm that he himself can't break.
↩