Ejemplo n.º 1
0
        private PinnedBuffer EncryptInCbcMode(PinnedBuffer plaintext, PinnedBuffer privateKey, PinnedBuffer initializationVector)
        {
            initializationVector.RejectIf().IsNull(nameof(initializationVector)).OrIf(argument => argument.Count() != BlockSizeInBytes, nameof(privateKey), "The length of the specified initialization vector is invalid for the algorithm.");

            using (var encryptionProvider = InitializeProvider())
            {
                encryptionProvider.BlockSize = BlockSizeInBits;
                encryptionProvider.KeySize   = KeySizeInBits;
                encryptionProvider.Mode      = Mode;
                encryptionProvider.Padding   = PaddingMode;
                encryptionProvider.Key       = privateKey;
                encryptionProvider.IV        = initializationVector;

                using (var encryptor = encryptionProvider.CreateEncryptor(privateKey, initializationVector))
                {
                    using (var memoryStream = new MemoryStream())
                    {
                        using (var cryptographicStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                        {
                            cryptographicStream.Write(plaintext, 0, plaintext.Length);
                            cryptographicStream.FlushFinalBlock();
                            return(new PinnedBuffer(initializationVector.Concat(memoryStream.ToArray()).ToArray(), false));
                        }
                    }
                }
            }
        }