Skip to content

Commit 075204c

Browse files
authored
Fix FromBase64Transform.TransformFinalBlock to consistently reset state (#124480)
1 parent f8ac08f commit 075204c

2 files changed

Lines changed: 32 additions & 0 deletions

File tree

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,7 @@ public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int input
189189

190190
if (inputCount == 0)
191191
{
192+
Reset();
192193
return Array.Empty<byte>();
193194
}
194195

src/libraries/System.Security.Cryptography/tests/Base64TransformsTests.cs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -439,5 +439,36 @@ public void TransformBlock_OutputBufferTooSmall_ThrowsArgumentOutOfRangeExceptio
439439
AssertExtensions.Throws<ArgumentOutOfRangeException>("outputBuffer",
440440
() => transform.TransformBlock(block, 0, block.Length, destination, 0));
441441
}
442+
443+
[Theory]
444+
[InlineData(0)]
445+
[InlineData(1)]
446+
public void TransformFinalBlock_ShouldResetStateConsistently(int finalBlockSize)
447+
{
448+
using FromBase64Transform transform = new();
449+
byte[] destination = new byte[2048];
450+
byte[] partialBlock = [(byte)'A'];
451+
byte[] finalBlock = new byte[finalBlockSize];
452+
finalBlock.AsSpan().Fill((byte)'A');
453+
454+
// First, do a TransformBlock with a partial block of one unit
455+
transform.TransformBlock(partialBlock, 0, partialBlock.Length, destination, 0);
456+
457+
// Call TransformFinalBlock with either zero or one input
458+
// This still results in a partial block (we need four for a complete block)
459+
byte[] transformed = transform.TransformFinalBlock(finalBlock, 0, finalBlockSize);
460+
461+
// The transform should return an empty buffer for partial blocks
462+
Assert.Empty(transformed);
463+
464+
// Now try to reuse the transform with a complete block
465+
// This should succeed without observing leftover data from before
466+
byte[] complete = Text.Encoding.UTF8.GetBytes(Convert.ToBase64String("Hello World"u8.ToArray()));
467+
transformed = transform.TransformFinalBlock(complete, 0, complete.Length);
468+
469+
// Verify we get the expected output
470+
string result = Text.Encoding.UTF8.GetString(transformed);
471+
Assert.Equal("Hello World", result);
472+
}
442473
}
443474
}

0 commit comments

Comments
 (0)