Skip to content

ChaCha7539Engine: allow the last counter block and refuse all keystream after it - #2571

Open
AlexLaroche wants to merge 2 commits into
bcgit:mainfrom
AlexLaroche:chacha7539-last-counter-block
Open

AlexLaroche wants to merge 2 commits into
bcgit:mainfrom
AlexLaroche:chacha7539-last-counter-block

Conversation

@AlexLaroche

@AlexLaroche AlexLaroche commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

ChaCha7539Engine (RFC 8439, 32-bit block counter) mishandles the end of the counter range in three ways:

  1. The last block can't be fully used. Salsa20Engine.processBytes/returnByte call advanceCounter() as soon as a block's last byte is used, and ChaCha7539Engine.advanceCounter() throws when the counter wraps. So a call that ends exactly on the last byte of block 0xFFFFFFFF, which RFC 8439 allows, throws even though all its output was valid. Starting at 0xFFFFFFFF, 1 and 63 bytes work but 64 bytes throw. Starting at 0xFFFFFFFE, 127 bytes work but 128 throw.
  2. Keystream is reused after a caught exception. When that throw happens, engineState[12] has already wrapped to 0 and the buffer still holds block 0xFFFFFFFF's keystream. A caller that catches the exception and keeps encrypting gets block 0xFFFFFFFF's keystream a second time, then block 1, 2, … again.
  3. A refused call has already written output. A call that runs past the end writes output up to the end of the counter before throwing.

These are all reachable through the public SkippingStreamCipher API (seekTo/skip). From counter 0 they only matter at the 256 GiB limit, which ChaCha20Poly1305's DATA_LIMIT = (2^32 - 1) * 64 also assumes is fully usable. Checked on main (e03fee0) and bcprov 1.87, with the Wycheproof chacha20_counter_test.json vectors (C2SP/wycheproof, ChaCha20-IETF group, tcIds 29–42).

Fix (ChaCha7539Engine only)

  • Position past the end. A private counterExhausted flag records that the counter has moved past 0xFFFFFFFF. With it set, getCounter() returns 2^32 instead of the wrapped 0, so getPosition() reports 2^38, the end of the stream.
  • Up-front checks. processBytes, returnByte and skip check the request against the bytes left (2^38 - getPosition()) before doing anything. A request that would go past the end throws the same IllegalStateException("attempt to increase counter past 2^32.") as before, but leaves the output and the position untouched.
  • Counter bookkeeping. advanceCounter/retreatCounter (both forms), getCounter and resetCounter go through one setCounter(long). The counter can now reach exactly 2^32, the exhausted state, but never pass it. Retreating from the end clears the flag, so skip(-n) from the end works. reset(), init() and seekTo() clear it too.
  • seekTo(2^38) (exactly the end of the stream) is now accepted. Anything past it is still refused.

XChaCha20Engine inherits the change. No public API changes.

Tests

  • New ChaCha7539CounterLimitTest (TestCase, registered in crypto.test.AllTests), public API only. Expected output is the Wycheproof keystream for tcIds 35 and 39 (all-zero key, nonce and message). It covers:

    • the last block, the last two, and an unaligned end, via processBytes and returnByte;
    • refusal past the end with the output buffer and position unchanged (tcIds 40–42);
    • the exhausted state staying refused;
    • seekTo to the end, and skip/seekTo past it;
    • skip backwards from the end;
    • reset restarting at block 0.

    All 9 fail on main (8 with the early IllegalStateException, 1 because output was written before the refusal). All pass with the change.

  • ChaChaTest, XChaCha20Test, ChaCha20Poly1305Test, XChaCha20Poly1305Test, Salsa20Test, XSalsa20Test, StreamCipherOverlapTest, SymmetricConstraintsTest and BigSkippingCipherTest.testSkipFromNonZeroCounterCarry, the only BigSkippingCipherTest case using ChaCha7539Engine, all pass. The rest of BigSkippingCipherTest (AES-CTR, Salsa20, 64-bit ChaCha) doesn't touch this class, and I stopped it after 35 minutes.

  • :core:compileJava :core:compileTestJava :core:checkstyleMain pass on JDK 25. The change uses no post-1.4 language features or APIs. I didn't run the prov or tls suites.

Release note added to docs/releasenotes.md (1.88, Defects Fixed).

The same defect in bc-csharp is bcgit/bc-csharp#757.

@AlexLaroche

Copy link
Copy Markdown
Contributor Author

Contribution statement

Use of generative AI. I used Claude Code (Anthropic's coding agent, model Claude Opus) to help with this pull request. It helped find and reproduce the issue, write the change and its regression test, run the existing tests, and write this description. I chose what to submit and I am responsible for it.

Review. I have reviewed every line of this change, including the tests and the release note, and I understand what it does and why. I checked that the new test fails on main and passes with the change, and that the existing tests listed in the description pass.

Representations under CONTRIBUTING.md. By submitting this pull request I make the representations in the project's contributing guidelines, including the following:

  • I hold the rights needed to release this contribution under the Bouncy Castle License. To the best of my knowledge it will not give rise to third-party intellectual property claims against the Legion of the Bouncy Castle Inc. or its recipients.
  • To the extent any part of it is protected by copyright, I am its author or am otherwise authorised to release it under the Bouncy Castle License.
  • Where any part was generated with AI tools and is not protected by copyright, I do not represent that part as owned intellectual property, and I understand that the Legion of the Bouncy Castle Inc. accepts it on that basis.
  • I have complied with Anthropic's terms of use for Claude Code. Those terms assign to me whatever rights Anthropic has in the outputs and place no restriction on contributing them under the Bouncy Castle License.
  • To the best of my knowledge, the contribution does not reproduce or derive from third-party material in a way that would infringe anyone's intellectual property rights. The code was written against the existing Bouncy Castle sources in this repository.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant