Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
reduce allocations in GCMBlockGipher
  • Loading branch information
lostmsu committed Jan 14, 2024
commit 4e9ea9cbd74cfdee7e507c13ea645f86bf017421
28 changes: 21 additions & 7 deletions crypto/src/crypto/modes/GCMBlockCipher.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
using System.Buffers;
using System.Runtime.CompilerServices;
#endif
#if NETCOREAPP3_0_OR_GREATER
Expand Down Expand Up @@ -988,7 +989,7 @@ public int DoFinal(Span<byte> output)
long c = (long)(((totalLength * 8) + 127) >> 7);

// Calculate the adjustment factor
byte[] H_c = new byte[16];
Span<byte> H_c = stackalloc byte[16];
if (exp == null)
{
exp = new BasicGcmExponentiator();
Expand Down Expand Up @@ -1042,23 +1043,36 @@ public int DoFinal(Span<byte> output)
}
#endif

public void Reset()
public void Reset()
{
Reset(true);
}

static void Reset<T>(ref T[] array, int size)
{
if (array is null || array.Length != size)
{
array = new T[size];
}
else
{
Arrays.Fill(array, default);
}
}

private void Reset(bool clearMac)
{
// note: we do not reset the nonce.

S = new byte[BlockSize];
S_at = new byte[BlockSize];
S_atPre = new byte[BlockSize];
atBlock = new byte[BlockSize];
Reset(ref S, BlockSize);
Reset(ref S_at, BlockSize);
Reset(ref S_atPre, BlockSize);
Reset(ref atBlock, BlockSize);
atBlockPos = 0;
atLength = 0;
atLengthPre = 0;
counter = Arrays.Clone(J0);
Reset(ref counter, BlockSize);
J0.CopyTo(counter, 0);
counter32 = Pack.BE_To_UInt32(counter, 12);
blocksRemaining = uint.MaxValue - 1;
bufOff = 0;
Expand Down