示例#1
0
        /// <inheritdoc />
        public override bool TryDecrypt(ReadOnlySpan <byte> ciphertext, ReadOnlySpan <byte> nonce, Span <byte> plaintext, out int bytesWritten)
        {
            if (ciphertext.IsEmpty)
            {
                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.ciphertext);
            }

            if (nonce.IsEmpty)
            {
                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.nonce);
            }

            if (_disposed)
            {
                ThrowHelper.ThrowObjectDisposedException(GetType());
            }

            Aes aes = _aesPool.Get();

            try
            {
                aes.IV = nonce.ToArray();
                using (var decryptor = aes.CreateDecryptor())
                {
                    bytesWritten = AesCbcHelper.Transform(decryptor, ciphertext, 0, ciphertext.Length, plaintext);
                }

                return(bytesWritten <= ciphertext.Length);
            }
            finally
            {
                _aesPool.Return(aes);
            }
        }
示例#2
0
        /// <inheritdoc />
        public override void Encrypt(
            ReadOnlySpan <byte> plaintext,
            ReadOnlySpan <byte> nonce,
            Span <byte> ciphertext)
        {
            if (_disposed)
            {
                ThrowHelper.ThrowObjectDisposedException(GetType());
            }

            byte[]? arrayToReturnToPool = null;
            Aes aes = _aesPool.Get();

            try
            {
                aes.IV = nonce.ToArray();
                using ICryptoTransform encryptor = aes.CreateEncryptor();
                AesCbcHelper.Transform(encryptor, plaintext, 0, plaintext.Length, ciphertext);
            }
            catch
            {
                CryptographicOperations.ZeroMemory(ciphertext);
                throw;
            }
            finally
            {
                _aesPool.Return(aes);
                if (arrayToReturnToPool != null)
                {
                    ArrayPool <byte> .Shared.Return(arrayToReturnToPool);
                }
            }
        }