Esempio n. 1
0
        protected void TryEncryptOneShot_DestinationJustRightTest(byte[] plaintext, byte[] ciphertext, PaddingMode padding, CipherMode mode, int feedbackSize = 0)
        {
            using (SymmetricAlgorithm alg = CreateAlgorithm())
            {
                int paddingSizeBytes = mode == CipherMode.CFB ? feedbackSize / 8 : alg.BlockSize / 8;
                alg.Key = Key;

                int expectedCiphertextSize = mode switch
                {
                    CipherMode.ECB => alg.GetCiphertextLengthEcb(plaintext.Length, padding),
                    CipherMode.CBC => alg.GetCiphertextLengthCbc(plaintext.Length, padding),
                    CipherMode.CFB => alg.GetCiphertextLengthCfb(plaintext.Length, padding, feedbackSize),
                    _ => throw new NotImplementedException(),
                };
                Span <byte> destinationBuffer = new byte[expectedCiphertextSize];

                int  bytesWritten;
                bool result = mode switch
                {
                    CipherMode.ECB => alg.TryEncryptEcb(plaintext, destinationBuffer, padding, out bytesWritten),
                    CipherMode.CBC => alg.TryEncryptCbc(plaintext, IV, destinationBuffer, out bytesWritten, padding),
                    CipherMode.CFB => alg.TryEncryptCfb(plaintext, IV, destinationBuffer, out bytesWritten, padding, feedbackSize),
                    _ => throw new NotImplementedException(),
                };
                Assert.True(result, "TryEncrypt");
                Assert.Equal(expectedCiphertextSize, bytesWritten);

                AssertCiphertexts(ciphertext, destinationBuffer, padding, paddingSizeBytes);
            }
        }