From afc3e2192bb3eed9f83558de3c34af8d61c2d9b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Philippe=20Dugr=C3=A9?= Date: Tue, 19 Nov 2024 08:52:04 -0500 Subject: [PATCH] Optimized out an allocation and avoid leaving un-zeroed data in RAM --- src/XTS.cs | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/src/XTS.cs b/src/XTS.cs index 2b86ab6..40149e4 100644 --- a/src/XTS.cs +++ b/src/XTS.cs @@ -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 bufferSpan = buffer.AsSpan(); Span previousBlockSpan = bufferSpan[previousBlockStart..currentBlockStart]; Span 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); } } @@ -210,6 +205,16 @@ private static void XorBlocksInPlace(ReadOnlySpan input, Span output } } + private static void SwapSpan(Span x, Span 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 tweak) { bool carry = false;