From b8d83729a92422e92c9827eaafea709afe6d1b36 Mon Sep 17 00:00:00 2001 From: Kevin Jones Date: Mon, 13 Jan 2025 14:32:13 -0500 Subject: [PATCH] Fix overflow in GetHexStringCore --- .../src/System/Security/Cryptography/RandomNumberGenerator.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RandomNumberGenerator.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RandomNumberGenerator.cs index 14d8635fd70fbf..d535cedc26ec61 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RandomNumberGenerator.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RandomNumberGenerator.cs @@ -313,7 +313,9 @@ private static void GetHexStringCore(Span destination, bool lowercase) // Don't overfill the buffer if the destination is smaller than the buffer size. We need to round up when // when dividing by two to account for an odd-length destination. - int needed = (destination.Length + 1) / 2; + // Adding one to a span of length int.MaxValue may overflow. This is handled by the unsigned shift to the right + // which will correct the overflow. + int needed = (destination.Length + 1) >>> 1; Span remainingRandom = randomBuffer.Slice(0, Math.Min(RandomBufferSize, needed)); RandomNumberGenerator.Fill(remainingRandom);