protected void TryDecryptOneShot_DestinationLargerTest(byte[] plaintext, byte[] ciphertext, PaddingMode padding, CipherMode mode, int feedbackSize = 0) { using (SymmetricAlgorithm alg = CreateAlgorithm()) { alg.Key = Key; int expectedPlaintextSize = padding == PaddingMode.Zeros ? ciphertext.Length : plaintext.Length; Span <byte> largeBuffer = new byte[expectedPlaintextSize + 10]; Span <byte> destinationBuffer = largeBuffer.Slice(0, expectedPlaintextSize); largeBuffer.Fill(0xCC); int bytesWritten; bool result = mode switch { CipherMode.ECB => alg.TryDecryptEcb(ciphertext, destinationBuffer, padding, out bytesWritten), CipherMode.CBC => alg.TryDecryptCbc(ciphertext, IV, destinationBuffer, out bytesWritten, padding), CipherMode.CFB => alg.TryDecryptCfb(ciphertext, IV, destinationBuffer, out bytesWritten, padding, feedbackSize), _ => throw new NotImplementedException(), }; Assert.True(result, "TryDecrypt"); Assert.Equal(destinationBuffer.Length, bytesWritten); AssertPlaintexts(plaintext, destinationBuffer, padding); Span <byte> excess = largeBuffer.Slice(destinationBuffer.Length); AssertExtensions.FilledWith <byte>(0xCC, excess); } }
protected void TryDecryptOneShot_DestinationTooSmallTest(byte[] plaintext, byte[] ciphertext, PaddingMode padding, CipherMode mode, int feedbackSize = 0) { if (plaintext.Length == 0) { // Can't have a ciphertext length shorter than zero. return; } using (SymmetricAlgorithm alg = CreateAlgorithm()) { alg.Key = Key; Span <byte> destinationBuffer = new byte[plaintext.Length - 1]; int bytesWritten; bool result = mode switch { CipherMode.ECB => alg.TryDecryptEcb(ciphertext, destinationBuffer, padding, out bytesWritten), CipherMode.CBC => alg.TryDecryptCbc(ciphertext, IV, destinationBuffer, out bytesWritten, padding), CipherMode.CFB => alg.TryDecryptCfb(ciphertext, IV, destinationBuffer, out bytesWritten, padding, feedbackSize), _ => throw new NotImplementedException(), }; Assert.False(result, "TryDecrypt"); Assert.Equal(0, bytesWritten); } }
protected void TryDecryptOneShot_DestinationJustRightTest(byte[] plaintext, byte[] ciphertext, PaddingMode padding, CipherMode mode) { using (SymmetricAlgorithm alg = CreateAlgorithm()) { alg.Key = Key; int expectedPlaintextSize = padding == PaddingMode.Zeros ? ciphertext.Length : plaintext.Length; Span <byte> destinationBuffer = new byte[expectedPlaintextSize]; int bytesWritten; bool result = mode switch { CipherMode.ECB => alg.TryDecryptEcb(ciphertext, destinationBuffer, padding, out bytesWritten), CipherMode.CBC => alg.TryDecryptCbc(ciphertext, IV, destinationBuffer, out bytesWritten, padding), _ => throw new NotImplementedException(), }; Assert.True(result, "TryDecrypt"); Assert.Equal(destinationBuffer.Length, bytesWritten); AssertPlaintexts(plaintext, destinationBuffer, padding); } }