Repository navigation
Speed up Base32.FromBase32 decoding for authenticator keys - #70227
Conversation
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]>
There was a problem hiding this comment.
🟢 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
|
/review |
DeagleGross
left a comment
There was a problem hiding this comment.
requesting change of approach
|
ASP.NET Core Perf 2 stopped: 🤖 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]>
|
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]>
|
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) |
|
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.
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]>
|
✅ 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
|
Speed up Base32.FromBase32 decoding for authenticator keys
Decode Base32 authenticator keys with range checks and a 5-bit accumulator, and validate authenticator codes without allocating the key
Description
Base32.FromBase32decodes the authenticator key on everyAuthenticatorTokenProvider.ValidateAsynccall, which is authenticator-app 2FA.The current decoder has two costs:
string.IndexOf(char.ToUpperInvariant(c))over the 32-char alphabet.output[outputIndex].This PR:
A-Z,a-zand2-7with three range checks. Other ASCII characters return invalid. Non-ASCII characters still use the originalIndexOf(char.ToUpperInvariant(c))lookup, so culture-invariant casing quirks are unchanged.Base32.TryFromBase32(ReadOnlySpan<char> input, Span<byte> destination, out int bytesWritten)(review feedback). It returnsfalsefor invalid characters or a too-small destination and clears any partially written bytes.FromBase32now delegates to it.AuthenticatorTokenProvider.ValidateAsyncdecodes the key withTryFromBase32into a fixed 128-bytestackallocbuffer (heap array for larger keys, no pooling) and zeroes it after use.Rfc6238AuthenticationService.ComputeTotptakes the key asReadOnlySpan<byte>. An invalid key still throwsFormatException.What stays the same:
FormatExceptionbehavior ofFromBase32andValidateAsyncare identical.FromBase32(it needs abyte[]forHMACSHA1). The decoded key array is now cleared after use.GenerateBase32andToBase32, is untouched.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,536charvalues 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-lineUserManagerchange). Keys come from a seeded RNG: 32 chars (20 bytes, the default authenticator key) and 320 chars (200 bytes).AuthenticatorTokenProvider.ValidateAsync, real ReleaseMicrosoft.Extensions.Identity.Core.dllfrom main vs this PR. A 7-digit token never matches, so all 5 TOTP window steps run, which is the worst case.FormatException)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.cssources from main, the previous PR head (8afec3a) and this head are compiled side by side in one process.FromBase32TryFromBase32into stack bufferFromBase32* Outlier round.
FromBase32is about 11 ns slower than the previous PR head (49 ns), because it now callsTryFromBase32. On .NET it no longer has a caller in the product. Only the netstandard2.0/net462 authenticator path uses it.Tests
Base32Testcases:f…foobar), with and without padding."MZ!").FormatExceptionfor invalid ASCII just outside each range (@ [ \{ 0 1 8), for!, space,=in the middle, and non-ASCII (é, Kelvin sign, fullwidthA`).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 pastbytesWritten.AuthenticatorTokenProviderTest: accepts the current code for 20-byte (stack) and 200-byte (heap fallback) keys, and throwsFormatExceptionfor an invalid key.Microsoft.AspNetCore.Identity.Test: 616 passed, 0 failed, 1 skipped.IdentityUIScriptsTestwas excluded because it needs CDN network access.Microsoft.AspNetCore.Identity.FunctionalTests2FA/authenticator tests: 26 passed.Microsoft.Extensions.Identity.Corebuilds for net12.0, netstandard2.0 and net462.🤖 Posted by ASP.NET Core Perf 2 (AI Agent)