Skip to content

Commit b8d8372

Browse files
authored
Fix overflow in GetHexStringCore
1 parent 812d504 commit b8d8372

File tree

1 file changed

+3
-1
lines changed

1 file changed

+3
-1
lines changed

src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RandomNumberGenerator.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -313,7 +313,9 @@ private static void GetHexStringCore(Span<char> destination, bool lowercase)
313313

314314
// Don't overfill the buffer if the destination is smaller than the buffer size. We need to round up when
315315
// when dividing by two to account for an odd-length destination.
316-
int needed = (destination.Length + 1) / 2;
316+
// Adding one to a span of length int.MaxValue may overflow. This is handled by the unsigned shift to the right
317+
// which will correct the overflow.
318+
int needed = (destination.Length + 1) >>> 1;
317319
Span<byte> remainingRandom = randomBuffer.Slice(0, Math.Min(RandomBufferSize, needed));
318320
RandomNumberGenerator.Fill(remainingRandom);
319321

0 commit comments

Comments
 (0)