From 640c976f5bc66caf95f9c1640b236ad606d1926c Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Fri, 28 Jul 2023 10:36:31 -0400 Subject: [PATCH] Fix replacement loop in Base64UrlEncoder.UnsafeDecode It was doing unnecessary work by starting the search from the beginning each time. --- src/Microsoft.IdentityModel.Tokens/Base64UrlEncoder.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.IdentityModel.Tokens/Base64UrlEncoder.cs b/src/Microsoft.IdentityModel.Tokens/Base64UrlEncoder.cs index a96179ca15..d30ec32dc8 100644 --- a/src/Microsoft.IdentityModel.Tokens/Base64UrlEncoder.cs +++ b/src/Microsoft.IdentityModel.Tokens/Base64UrlEncoder.cs @@ -207,10 +207,12 @@ internal static unsafe byte[] UnsafeDecode(ReadOnlyMemory str) if (needReplace) { + Span remaining = charsSpan; int pos; - while ((pos = charsSpan.IndexOfAny(base64UrlCharacter62, base64UrlCharacter63)) >= 0) + while ((pos = remaining.IndexOfAny(base64UrlCharacter62, base64UrlCharacter63)) >= 0) { - charsSpan[pos] = charsSpan[pos] == base64UrlCharacter62 ? base64Character62 : base64Character63; + remaining[pos] = (remaining[pos] == base64UrlCharacter62) ? base64Character62 : base64Character63; + remaining = remaining.Slice(pos + 1); } }