Skip to content

Commit

Permalink
Optimized out an allocation and avoid leaving un-zeroed data in RAM
Browse files Browse the repository at this point in the history
  • Loading branch information
pdugre committed Nov 19, 2024
1 parent 9f33445 commit afc3e21
Showing 1 changed file with 14 additions and 9 deletions.
23 changes: 14 additions & 9 deletions src/XTS.cs
Original file line number Diff line number Diff line change
Expand Up @@ -146,20 +146,15 @@ private static void ProcessXtsSector(ICryptoTransform alg, byte[] buffer, int bu
int previousBlockStart = bufferOffset + (nFullBlocks - 1) * blockSize;
int currentBlockStart = previousBlockStart + blockSize;

// Define the spans
Span<byte> bufferSpan = buffer.AsSpan();
Span<byte> previousBlockSpan = bufferSpan[previousBlockStart..currentBlockStart];
Span<byte> currentBlockSpan = bufferSpan[currentBlockStart..(bufferOffset + bufferLength)];

// Buffer last bytes
byte[] remainingBytesArray = currentBlockSpan.ToArray();

// We copy part of the previous ciphertext at the end
previousBlockSpan[..remainingBytes].CopyTo(currentBlockSpan);

// We compute the last block on the previous block
// We only need to copy the start of the last block, as the end of the previous block is already there
remainingBytesArray.AsSpan().CopyTo(previousBlockSpan);
// We copy part of the previous ciphertext at the end and replace it with the plaintext of the last block
SwapSpan(previousBlockSpan[..remainingBytes], currentBlockSpan);

// We encrypt/decrypt the second to last block
TransformBlock(alg, buffer, previousBlockStart, tweak);
}
}
Expand Down Expand Up @@ -210,6 +205,16 @@ private static void XorBlocksInPlace(ReadOnlySpan<byte> input, Span<byte> output
}
}

private static void SwapSpan(Span<byte> x, Span<byte> y)
{
for (int i = 0; i < x.Length; i++)
{
byte tmp = x[i];
x[i] = y[i];
y[i] = tmp;
}
}

private static void GaloisMultiplyByTwo(Span<byte> tweak)
{
bool carry = false;
Expand Down

0 comments on commit afc3e21

Please sign in to comment.