Skip to content

Commit 51dec55

Browse files
committed
address PR comments
1 parent f233b4e commit 51dec55

File tree

2 files changed

+17
-5
lines changed

2 files changed

+17
-5
lines changed

src/DataProtection/DataProtection/src/KeyManagement/KeyRingBasedDataProtector.cs

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -368,8 +368,9 @@ internal static byte[] BuildAadTemplateBytes(string[] purposes)
368368
int totalPurposeLen = 4 + keySize + 4;
369369

370370
int[]? lease = null;
371-
Span<int> purposeLengthsPool = purposes.Length <= 32 ? stackalloc int[purposes.Length] : (lease = ArrayPool<int>.Shared.Rent(purposes.Length)).AsSpan(0, purposes.Length);
372-
for (int i = 0; i < purposes.Length; i++)
371+
var targetLength = purposes.Length;
372+
Span<int> purposeLengthsPool = targetLength <= 32 ? stackalloc int[targetLength] : (lease = ArrayPool<int>.Shared.Rent(targetLength)).AsSpan(0, targetLength);
373+
for (int i = 0; i < targetLength; i++)
373374
{
374375
string purpose = purposes[i];
375376

@@ -387,10 +388,10 @@ internal static byte[] BuildAadTemplateBytes(string[] purposes)
387388
BinaryPrimitives.WriteUInt32BigEndian(targetSpan.Slice(0), MAGIC_HEADER_V0);
388389
// index 4: key (skipped for now, will be populated in `GetAadForKey()`)
389390
// index 4 + keySize: purposeCount
390-
BinaryPrimitives.WriteInt32BigEndian(targetSpan.Slice(4 + keySize), purposes.Length);
391+
BinaryPrimitives.WriteInt32BigEndian(targetSpan.Slice(4 + keySize), targetLength);
391392

392-
int index = 4 + keySize + 4; // starting from first purpose
393-
for (int i = 0; i < purposes.Length; i++)
393+
int index = 4 /* MAGIC_HEADER_V0 */ + keySize + 4 /* purposeLength */; // starting from first purpose
394+
for (int i = 0; i < targetLength; i++)
394395
{
395396
string purpose = purposes[i];
396397

src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/KeyManagement/AdditionalAuthenticatedDataTemplateTests.cs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,4 +36,15 @@ public void AdditionalAuthenticatedDataTemplateBuildAadTemplateBytes_ReturnsSame
3636
var actualBytesInBase64 = Convert.ToBase64String(actualBytes);
3737
Assert.Equal(expectedBytesInBase64, actualBytesInBase64);
3838
}
39+
40+
[Fact]
41+
public void AdditionalAuthenticatedDataTemplateBuildAadTemplateBytes_ThrowsOnIllegalUtf8Text()
42+
{
43+
Assert.Throws<EncoderFallbackException>(() =>
44+
{
45+
var actualBytes = KeyRingBasedDataProtector.AdditionalAuthenticatedDataTemplate.BuildAadTemplateBytes([
46+
"😀"[0] + "X",
47+
]);
48+
});
49+
}
3950
}

0 commit comments

Comments
 (0)