Skip to content

Speed up Base32.FromBase32 decoding for authenticator keys - #70227

Merged
DeagleGross merged 4 commits into
mainfrom
perf/identity-base32-decode
Nov 11, 2026
Merged

DeagleGross merged 4 commits into
mainfrom
perf/identity-base32-decode

Conversation

@davidfowl

@davidfowl davidfowl commented Nov 1, 2026 •

Copy link
Copy Markdown
Member

Speed up Base32.FromBase32 decoding for authenticator keys

  • You've read the Contributor Guide and Code of Conduct.
  • You've included unit or integration tests for your change, where applicable.
  • You've included inline docs for your change, where applicable.
  • There's an open issue for the PR that you are making. If you'd like to propose a new feature or change, please open an issue to discuss the change or find an existing issue.

Decode Base32 authenticator keys with range checks and a 5-bit accumulator, and validate authenticator codes without allocating the key

Description

Base32.FromBase32 decodes the authenticator key on every AuthenticatorTokenProvider.ValidateAsync call, which is authenticator-app 2FA.

The current decoder has two costs:

  • Per character, it does a string.IndexOf(char.ToUpperInvariant(c)) over the 32-char alphabet.
  • Its loop moves only 1–5 bits per iteration. For a 32-char key that's about 52 iterations, each with a read-modify-write of output[outputIndex].

This PR:

  • Maps A-Z, a-z and 2-7 with three range checks. Other ASCII characters return invalid. Non-ASCII characters still use the original IndexOf(char.ToUpperInvariant(c)) lookup, so culture-invariant casing quirks are unchanged.
  • Uses a standard 5-bit accumulator that emits a byte whenever at least 8 bits are buffered.
  • Adds an internal, non-throwing Base32.TryFromBase32(ReadOnlySpan<char> input, Span<byte> destination, out int bytesWritten) (review feedback). It returns false for invalid characters or a too-small destination and clears any partially written bytes. FromBase32 now delegates to it.
  • On .NET, AuthenticatorTokenProvider.ValidateAsync decodes the key with TryFromBase32 into a fixed 128-byte stackalloc buffer (heap array for larger keys, no pooling) and zeroes it after use. Rfc6238AuthenticationService.ComputeTotp takes the key as ReadOnlySpan<byte>. An invalid key still throws FormatException.

What stays the same:

  • Decoding still stops when the output is full. It consumes and validates exactly the same characters as before, so trailing unused characters are still not validated.
  • Output bytes and FormatException behavior of FromBase32 and ValidateAsync are identical.
  • The netstandard2.0/net462 path still uses FromBase32 (it needs a byte[] for HMACSHA1). The decoded key array is now cleared after use.
  • The encoding side, GenerateBase32 and ToBase32, is untouched.
  • No public API changes.

Equivalence check, run outside the repo: old and new decoders compared on 2,000,000 random strings of length 0–39. Inputs were drawn from valid characters, lowercase, =, digits 0/1/8/9, space and assorted non-ASCII characters. The check also covered all 65,536 char values as an 8-char string. Bytes and exception types matched in every case.

Benchmarks

net12.0, BenchmarkDotNet (InProcess, MemoryDiagnoser, 3 warmup / 15 iterations), 3 interleaved rounds on the final head. Baseline is the PR's merge-base 4f556f73 (main's Identity.Core differs only by an unrelated one-line UserManager change). Keys come from a seeded RNG: 32 chars (20 bytes, the default authenticator key) and 320 chars (200 bytes).

AuthenticatorTokenProvider.ValidateAsync, real Release Microsoft.Extensions.Identity.Core.dll from main vs this PR. A 7-digit token never matches, so all 5 TOTP window steps run, which is the worst case.

Case main (R1 / R2 / R3) PR (R1 / R2 / R3) Allocated main → PR
32-char key, no match 6157 / 6339 / 6130 ns 5996 / 6110 / 6105 ns 48 B → 0 B
320-char key (heap fallback), no match 9542 / 8947 / 9139 ns 7390 / 7686 / 7317 ns 224 B → 224 B
Invalid key (throws FormatException) 3517 / 3381 / 3330 ns 3514 / 3019 / 3044 ns 1280 B → 904 B

HMAC dominates the 32-char case, so the time difference is within noise. The win there is removing the per-call key allocation.

Decoder only. The Base32.cs sources from main, the previous PR head (8afec3a) and this head are compiled side by side in one process.

Case main FromBase32 PR Allocated main → PR
Valid 32 chars, TryFromBase32 into stack buffer 252 / 230 / 238 ns 50.1 / 49.9 / 50.0 ns 48 B → 0 B
Valid 32 chars, FromBase32 252 / 230 / 238 ns 59.9 / 61.2 / 60.8 ns 48 B → 48 B
Valid 320 chars (worst case) 2219 / 6094* / 2221 ns 474 / 460 / 464 ns 224 B → 0 B
Invalid first char (early exit) 1378 / 1411 / 1394 ns (throws) 4.5 / 4.3 / 5.0 ns 368 B → 0 B
Invalid last consumed char 1800 / 1677 / 1621 ns (throws) 48.8 / 48.7 / 47.5 ns 368 B → 0 B

* Outlier round. FromBase32 is about 11 ns slower than the previous PR head (49 ns), because it now calls TryFromBase32. On .NET it no longer has a caller in the product. Only the netstandard2.0/net462 authenticator path uses it.

Tests

  • New Base32Test cases:
    • RFC 4648 test vectors (f … foobar), with and without padding.
    • Lowercase input, all-zero and all-one groups, and inputs too short to produce a byte.
    • Unconsumed trailing characters, which are still not validated ("MZ!").
    • FormatException for invalid ASCII just outside each range (@ [ \ { 0 1 8), for !, space, = in the middle, and non-ASCII (é, Kelvin sign, fullwidth A`).
    • TryFromBase32: vectors, random round-trips for 0–64 bytes, empty and all-padding input, invalid characters (first, middle and last) with partial output cleared, destination too small, and a larger destination left untouched past bytesWritten.
  • New AuthenticatorTokenProviderTest: accepts the current code for 20-byte (stack) and 200-byte (heap fallback) keys, and throws FormatException for an invalid key.
  • Microsoft.AspNetCore.Identity.Test: 616 passed, 0 failed, 1 skipped. IdentityUIScriptsTest was excluded because it needs CDN network access.
  • Microsoft.AspNetCore.Identity.FunctionalTests 2FA/authenticator tests: 26 passed.
  • Microsoft.Extensions.Identity.Core builds for net12.0, netstandard2.0 and net462.

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

Map ASCII Base32 characters with range checks instead of
string.IndexOf(char.ToUpperInvariant(c)) per character, and accumulate 5 bits
per character instead of copying 1-5 bits per loop iteration. Non-ASCII
characters still go through the original ToUpperInvariant lookup, so decoded
bytes and FormatException behavior are unchanged.

Co-authored-by: Copilot <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 1, 2026 16:00
@github-actions github-actions Bot added the area-identity Includes: Identity and providers label Nov 1, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

The Base32 decoder optimization has no active review issues.

No open issues 🎉

What changed in this PR

This PR optimizes Identity’s Base32 decoder, reducing work performed during authenticator-key decoding without changing the encoding path or public API.

Changes:

  • Replaces repeated alphabet searches with ASCII range checks, retaining the existing non-ASCII fallback.
  • Uses a 5-bit accumulator to assemble output bytes while preserving trailing-character handling.
  • Adds decoding vectors and regression tests for lowercase input, short inputs, ignored trailing characters, and invalid characters.
File Description
src/​Identity/​test/​Identity.Test/​Base32Test.cs Adds decoding and invalid-input regression coverage.
src/​Identity/​Extensions.Core/​src/​Base32.cs Optimizes character lookup and byte assembly in FromBase32.

Review effort: Balanced

@PureWeen

PureWeen commented Nov 2, 2026

Copy link
Copy Markdown
Member

/review

@davidfowl davidfowl added the agent:working An AI agent is actively working on this issue/PR label Nov 6, 2026 — with Copilot SWE Agent
@davidfowl davidfowl removed the agent:working An AI agent is actively working on this issue/PR label Nov 6, 2026

@DeagleGross DeagleGross left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

requesting change of approach

@davidfowl davidfowl added the agent:working An AI agent is actively working on this issue/PR label Nov 10, 2026 — with Copilot SWE Agent
@davidfowl davidfowl removed the agent:working An AI agent is actively working on this issue/PR label Nov 10, 2026
@davidfowl davidfowl added the agent:working An AI agent is actively working on this issue/PR label Nov 11, 2026 — with Copilot SWE Agent

davidfowl commented Nov 11, 2026 •

Copy link
Copy Markdown
Member Author

ASP.NET Core Perf 2 stopped: TryFromBase32 is pushed and the review thread is answered.

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

Per review feedback, add a non-throwing internal TryFromBase32 that decodes
into a caller-provided span. FromBase32 now delegates to it, and
AuthenticatorTokenProvider.ValidateAsync decodes the key into a stack
buffer (heap fallback for large keys) that is cleared after use, removing
the per-call key allocation. ComputeTotp takes the key as ReadOnlySpan<byte>.

Co-authored-by: Copilot <[email protected]>
@davidfowl davidfowl removed the agent:working An AI agent is actively working on this issue/PR label Nov 11, 2026
@davidfowl davidfowl added the agent:working An AI agent is actively working on this issue/PR label Nov 11, 2026 — with Copilot SWE Agent

davidfowl commented Nov 11, 2026 •

Copy link
Copy Markdown
Member Author

ASP.NET Core Perf 2 stopped: the latest review comments are addressed in e4b9e79 and the threads are answered.

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

Inline the 128-byte stackalloc threshold and rent from ArrayPool for larger
keys, zeroing the buffer before returning it.

Co-authored-by: Copilot <[email protected]>
@davidfowl davidfowl removed the agent:working An AI agent is actively working on this issue/PR label Nov 11, 2026
@davidfowl davidfowl added the agent:working An AI agent is actively working on this issue/PR label Nov 11, 2026 — with Copilot SWE Agent

davidfowl commented Nov 11, 2026 •

Copy link
Copy Markdown
Member Author

ASP.NET Core Perf 2 stopped: CI classified as unrelated (evidence above) and the try/finally fix pushed in 2cdb18d.

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

Copy link
Copy Markdown
Member Author

CI on e4b9e79: the red checks come from a single Helix work-item failure with no failing tests. It doesn't look related to this change.

  • aspnetcore-ci (build 1675279) reports Failed: 0, Passed 87,366, Other 1,065 out of 88,431 tests. The only errors are on Helix tests Monitor Helix Jobs: "Failed work item information" (log L114) and "Helix job monitor failed (exit code '1')". That pattern means a work item crashed, timed out or hit an infra problem without reporting a test failure. Build Analysis and Build Insights are red only because they roll up that one job.
  • I couldn't open the AzDO/Helix log from my environment, so I can't name the work item.
  • Why I think it's unrelated:
    • The only change since the fully green 818190b is about 6 lines in AuthenticatorTokenProvider.ValidateAsync: an ArrayPool rent for keys over 128 bytes.
    • Microsoft.AspNetCore.Identity.Test passes locally at this head. All Base32Test and AuthenticatorTokenProviderTest cases pass, including the pooled path. The only local failures are the IdentityUIScriptsTest CDN checks, which need internet access my environment doesn't have.
    • The earlier heads 8afec3a and 818190b passed aspnetcore-ci, including Helix.

I'm pushing a follow-up commit for the review feedback (try/finally around the rented buffer), so CI will run again on the new head. No retrigger needed.

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

Start the try block right after renting so the FormatException path also zeroes and returns the buffer.

Co-authored-by: Copilot <[email protected]>
@davidfowl davidfowl removed the agent:working An AI agent is actively working on this issue/PR label Nov 11, 2026
@DeagleGross
DeagleGross merged commit 0a1449f into main Nov 11, 2026
27 checks passed
@DeagleGross
DeagleGross deleted the perf/identity-base32-decode branch November 11, 2026 16:10
@github-actions

Copy link
Copy Markdown
Contributor

✅ No documentation PR was created.

Confidence that documentation is needed: 3%

No docs needed: this is an internal performance optimization of Base32 decoding and authenticator code validation with no public API or observable behavior change.

Documentation surfaces considered

  • Conceptual article: Not required — Internal perf refactor; internal TryFromBase32 only, no public API, defaults, or behavior change. Signals: no_signal.
  • Migration guidance: Not required — No user action needed when upgrading.
  • Breaking change: Not required — No compatibility impact; outputs and FormatException behavior are identical.

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — 2cdb18de Deployed Nov 11, 2026 by DeagleGross via conclusion #295
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-identity Includes: Identity and providers

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants