From dabd91004d9259abcac898f2bd4bd86f19b8bea1 Mon Sep 17 00:00:00 2001
From: Stephen Toub <stoub@microsoft.com>
Date: Tue, 23 Jul 2024 13:38:47 -0400
Subject: [PATCH] Fix invalid IndexOutOfRangeException in Convert

---
 .../System.Private.CoreLib/src/System/Convert.cs     |  4 ++--
 .../System/Convert.cs                                | 12 ++++++++++++
 2 files changed, 14 insertions(+), 2 deletions(-)

diff --git a/src/libraries/System.Private.CoreLib/src/System/Convert.cs b/src/libraries/System.Private.CoreLib/src/System/Convert.cs
index cee646eeb9fe69..8c95cd6eeb976c 100644
--- a/src/libraries/System.Private.CoreLib/src/System/Convert.cs
+++ b/src/libraries/System.Private.CoreLib/src/System/Convert.cs
@@ -2397,7 +2397,7 @@ public static unsafe int ToBase64CharArray(byte[] inArray, int offsetIn, int len
 
             ArgumentOutOfRangeException.ThrowIfGreaterThan(offsetIn, inArrayLength - length);
 
-            if (inArrayLength == 0)
+            if (length == 0)
                 return 0;
 
             // This is the maximally required length that must be available in the char array
@@ -2798,7 +2798,7 @@ public static byte[] FromBase64CharArray(char[] inArray, int offset, int length)
             ArgumentOutOfRangeException.ThrowIfNegative(offset);
             ArgumentOutOfRangeException.ThrowIfGreaterThan(offset, inArray.Length - length);
 
-            if (inArray.Length == 0)
+            if (length == 0)
             {
                 return Array.Empty<byte>();
             }
diff --git a/src/libraries/System.Runtime/tests/System.Runtime.Extensions.Tests/System/Convert.cs b/src/libraries/System.Runtime/tests/System.Runtime.Extensions.Tests/System/Convert.cs
index 90833679760897..fa0233a2321264 100644
--- a/src/libraries/System.Runtime/tests/System.Runtime.Extensions.Tests/System/Convert.cs
+++ b/src/libraries/System.Runtime/tests/System.Runtime.Extensions.Tests/System/Convert.cs
@@ -32,6 +32,12 @@ public static void ToBase64CharArrayTest()
             Assert.Equal(344, length2);
         }
 
+        [Fact]
+        public static void ToBase64CharArray_NonEmptyInput_ZeroLength_Test()
+        {
+            Assert.Equal(0, Convert.ToBase64CharArray(new byte[1], 0, 0, new char[0], 0, Base64FormattingOptions.None));
+        }
+
         [Fact]
         public static void ToBase64StringTest()
         {
@@ -77,6 +83,12 @@ public static void Base64_AllMethodsRoundtripConsistently()
             }
         }
 
+        [Fact]
+        public static void FromBase64CharArray_NonEmptyInputZeroLength_ReturnsEmptyArray()
+        {
+            Assert.Same(Array.Empty<byte>(), Convert.FromBase64CharArray(new char[42], 0, 0));
+        }
+
         [Fact]
         public void ToBooleanTests()
         {