Skip to content

Commit 49eab48

Browse files
committed
dont allocate for prf-output as well
1 parent 6ec76d3 commit 49eab48

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

src/DataProtection/DataProtection/src/SP800_108/ManagedSP800_108_CTR_HMACSHA512.cs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// The .NET Foundation licenses this file to you under the MIT license.
33

44
using System;
5+
using System.Buffers;
56
using System.Security.Cryptography;
67
using Microsoft.AspNetCore.Cryptography;
78
using Microsoft.AspNetCore.DataProtection.Managed;
@@ -72,6 +73,8 @@ public static void DeriveKeys(
7273
{
7374
// See SP800-108, Sec. 5.1 for the format of the input to the PRF routine.
7475
var prfInput = new byte[checked(sizeof(uint) /* [i]_2 */ + label.Length + 1 /* 0x00 */ + (contextHeader.Length + contextData.Length) + sizeof(uint) /* [K]_2 */)];
76+
//var prfInputLength = checked(sizeof(uint) /* [i]_2 */ + label.Length + 1 /* 0x00 */ + (contextHeader.Length + contextData.Length) + sizeof(uint) /* [K]_2 */);
77+
//var prfInput = ArrayPool<byte>.Shared.Rent(prfInputLength);
7578

7679
// Copy [L]_2 to prfInput since it's stable over all iterations
7780
uint outputSizeInBits = (uint)checked((int)outputCount * 8);
@@ -95,7 +98,13 @@ public static void DeriveKeys(
9598
prfInput[3] = (byte)(i);
9699

97100
// Run the PRF and copy the results to the output buffer
101+
#if NET10_0_OR_GREATER
102+
var prfOutput = ArrayPool<byte>.Shared.Rent(prfOutputSizeInBytes);
103+
prf.TryComputeHash(prfInput, prfOutput, out _);
104+
#else
98105
var prfOutput = prf.ComputeHash(prfInput);
106+
#endif
107+
99108
CryptoUtil.Assert(prfOutputSizeInBytes == prfOutput.Length, "prfOutputSizeInBytes == prfOutput.Length");
100109
var numBytesToCopyThisIteration = Math.Min(prfOutputSizeInBytes, outputCount);
101110

@@ -117,7 +126,11 @@ public static void DeriveKeys(
117126
validationSubKeyIndex += leftOverBytes;
118127
}
119128

129+
#if NET10_0_OR_GREATER
130+
ArrayPool<byte>.Shared.Return(prfOutput, clearArray: true); // contains key material, so delete it
131+
#else
120132
Array.Clear(prfOutput, 0, prfOutput.Length); // contains key material, so delete it
133+
#endif
121134
outputCount -= numBytesToCopyThisIteration;
122135
}
123136
}

0 commit comments

Comments
 (0)