< Summary

Information
Class: System.IO.Compression.WinZipAesStream
Assembly: System.IO.Compression
File(s): D:\runner\runtime\src\libraries\System.IO.Compression\src\System\IO\Compression\WinZipAesStream.cs
Line coverage
83%
Covered lines: 336
Uncovered lines: 68
Coverable lines: 404
Total lines: 674
Line coverage: 83.1%
Branch coverage
66%
Covered branches: 87
Total branches: 130
Branch coverage: 66.9%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Cyclomatic complexity NPath complexity Sequence coverage
.ctor(...)66.66%6687.5%
GetSaltSize(...)50%2266.66%
CreateKey(...)50%2266.66%
Create(...)75%4481.81%
CreateAsync(...)50%4481.81%
ReadAndValidateHeaderCore(...)80%101085.71%
FinalizeAndCompareHMAC(...)50%6663.63%
ValidateAuthCode()100%22100%
ValidateAuthCodeAsync(...)100%22100%
WriteHeaderAsync(...)100%11100%
WriteHeader()100%11100%
ProcessBlock(...)83.33%66100%
GenerateKeystreamBuffer()100%22100%
XorBytes(...)100%22100%
WriteAuthCodeCoreAsync(...)62.5%8878.94%
ThrowIfNotReadable()50%2266.66%
GetBytesToRead(...)100%22100%
Read(...)100%11100%
Read(...)60%101088.46%
ReadAsync(...)100%110%
ReadAsync(...)60%101088.46%
GetWriteWorkBuffer()50%22100%
WriteCore(...)100%22100%
ThrowIfNotWritable()50%2266.66%
Write(...)100%11100%
Write(...)50%22100%
WriteAsync(...)100%110%
WriteAsyncCore(...)75%44100%
WriteAsync(...)100%11100%
Dispose(...)75%121291.66%
DisposeAsync()64.28%141490%
FinishEncryptingAsync(...)50%8857.14%
Flush()100%110%
FlushAsync(...)100%110%
Seek(...)100%110%
SetLength(...)100%110%

File(s)

D:\runner\runtime\src\libraries\System.IO.Compression\src\System\IO\Compression\WinZipAesStream.cs

#LineLine coverage
 1// Licensed to the .NET Foundation under one or more agreements.
 2// The .NET Foundation licenses this file to you under the MIT license.
 3
 4using System.Buffers.Binary;
 5using System.Diagnostics;
 6using System.Runtime.Versioning;
 7using System.Security.Cryptography;
 8using System.Text;
 9using System.Threading;
 10using System.Threading.Tasks;
 11
 12namespace System.IO.Compression
 13{
 14    internal sealed class WinZipAesStream : Stream
 15    {
 16        private const int BlockSize = 16; // AES block size in bytes
 17        private const int KeystreamBufferSize = 4096; // Pre-generate 4KB of keystream (256 blocks)
 18
 19        private readonly Stream _baseStream;
 20        private readonly bool _encrypting;
 21        private readonly Aes _aes;
 22        private IncrementalHash? _hmac;
 34423        private UInt128 _counter = 1;
 24        private readonly byte[] _salt;
 25        private readonly byte[] _passwordVerifier;
 26        private bool _headerWritten;
 27        private bool _disposed;
 28        // During decryption: set to true after the stored auth code is read and verified.
 29        // During encryption: set to true after the computed auth code has been written.
 30        private bool _authCodeFinalized;
 31        private readonly long _totalStreamSize;
 32        private readonly bool _leaveOpen;
 33        private readonly long _encryptedDataSize;
 34        private long _encryptedDataRemaining;
 35        // Pre-generated keystream buffer for efficiency
 34436        private readonly byte[] _keystreamBuffer = new byte[KeystreamBufferSize];
 34437        private int _keystreamOffset = KeystreamBufferSize; // Start depleted to force initial generation
 38
 39        // Reusable work buffer for write operations, lazily allocated on first write
 40        private byte[]? _writeWorkBuffer;
 41
 42        internal static int GetSaltSize(int keySizeBits)
 17243        {
 17244            if (OperatingSystem.IsBrowser())
 045            {
 046                throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnBrowser);
 47            }
 48
 17249            return WinZipAesKeyMaterial.GetSaltSize(keySizeBits);
 17250        }
 51
 52        /// <summary>
 53        /// Derives key material from a password and optional salt.
 54        /// </summary>
 55        internal static WinZipAesKeyMaterial CreateKey(ReadOnlySpan<char> password, byte[]? salt, int keySizeBits)
 51656        {
 51657            if (OperatingSystem.IsBrowser())
 058            {
 059                throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnBrowser);
 60            }
 51661            return WinZipAesKeyMaterial.Create(password, salt, keySizeBits);
 51662        }
 63
 64        /// <summary>
 65        /// Creates a WinZipAesStream synchronously. Reads and validates the header for decryption.
 66        /// </summary>
 67        internal static WinZipAesStream Create(Stream baseStream, WinZipAesKeyMaterial keyMaterial, long totalStreamSize
 34468        {
 34469            if (OperatingSystem.IsBrowser())
 070            {
 071                throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnBrowser);
 72            }
 73
 34474            ArgumentNullException.ThrowIfNull(baseStream);
 75
 34476            if (!encrypting)
 17277            {
 17278                ReadAndValidateHeaderCore(isAsync: false, baseStream, keyMaterial, CancellationToken.None).GetAwaiter().
 8679            }
 80
 25881            return new WinZipAesStream(baseStream, keyMaterial, totalStreamSize, encrypting, leaveOpen);
 25882        }
 83
 84        /// <summary>
 85        /// Creates a WinZipAesStream asynchronously. Reads and validates the header for decryption.
 86        /// </summary>
 87        internal static async Task<WinZipAesStream> CreateAsync(Stream baseStream, WinZipAesKeyMaterial keyMaterial, lon
 17288        {
 17289            if (OperatingSystem.IsBrowser())
 090            {
 091                throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnBrowser);
 92            }
 93
 17294            ArgumentNullException.ThrowIfNull(baseStream);
 95
 17296            if (!encrypting)
 17297            {
 17298                await ReadAndValidateHeaderCore(isAsync: true, baseStream, keyMaterial, cancellationToken).ConfigureAwai
 8699            }
 100
 86101            return new WinZipAesStream(baseStream, keyMaterial, totalStreamSize, encrypting, leaveOpen);
 86102        }
 103
 104        /// <summary>
 105        /// Reads and validates the WinZip AES header (salt + password verifier) from the stream.
 106        /// </summary>
 107        private static async Task ReadAndValidateHeaderCore(bool isAsync, Stream baseStream, WinZipAesKeyMaterial keyMat
 344108        {
 344109            if (OperatingSystem.IsBrowser())
 0110            {
 0111                throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnBrowser);
 112            }
 344113            int saltSize = keyMaterial.SaltSize;
 114
 115            // Read salt from stream
 344116            byte[] fileSalt = new byte[saltSize];
 344117            if (isAsync)
 172118            {
 172119                await baseStream.ReadExactlyAsync(fileSalt, cancellationToken).ConfigureAwait(false);
 172120            }
 121            else
 172122            {
 172123                baseStream.ReadExactly(fileSalt);
 172124            }
 125
 126            // Read the 2-byte password verifier from stream
 344127            byte[] verifier = new byte[2];
 344128            if (isAsync)
 172129            {
 172130                await baseStream.ReadExactlyAsync(verifier, cancellationToken).ConfigureAwait(false);
 172131            }
 132            else
 172133            {
 172134                baseStream.ReadExactly(verifier);
 172135            }
 136
 137            // Verify the salt matches. In WinZip AES, the salt is stored in the archive
 138            // header and is not secret; FixedTimeEquals is used here for consistency.
 344139            if (!CryptographicOperations.FixedTimeEquals(fileSalt, keyMaterial.Salt))
 0140            {
 0141                throw new InvalidDataException(SR.LocalFileHeaderCorrupt);
 142            }
 143
 144            // Compare the 2-byte password verifier. This is a weak check (only 2 bytes) used to
 145            // fail fast on an obviously wrong password; it is not a security guarantee.
 344146            if (!CryptographicOperations.FixedTimeEquals(verifier, keyMaterial.PasswordVerifier))
 172147            {
 172148                throw new InvalidDataException(SR.InvalidPassword);
 149            }
 172150        }
 151
 152        /// <summary>
 153        /// Private constructor â€” used by Create/CreateAsync.
 154        /// For decryption, the header must already be validated before calling this constructor.
 155        /// </summary>
 344156        private WinZipAesStream(Stream baseStream, WinZipAesKeyMaterial keyMaterial, long totalStreamSize, bool encrypti
 344157        {
 344158            if (OperatingSystem.IsBrowser())
 0159            {
 0160                throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnBrowser);
 161            }
 162
 344163            _baseStream = baseStream;
 164
 344165            Debug.Assert((totalStreamSize >= 0) == !encrypting, "Total stream size must be known when decrypting");
 166
 344167            _encrypting = encrypting;
 344168            _totalStreamSize = totalStreamSize;
 344169            _leaveOpen = leaveOpen;
 170
 344171            _aes = Aes.Create();
 172
 344173            _salt = keyMaterial.Salt;
 344174            _passwordVerifier = keyMaterial.PasswordVerifier;
 175
 344176            if (encrypting)
 172177            {
 172178                _encryptedDataSize = -1;
 172179                _encryptedDataRemaining = -1;
 172180            }
 181            else
 172182            {
 172183                int headerSize = checked(keyMaterial.SaltSize + 2); // Salt + Password Verifier
 184                const int hmacSize = 10; // 10-byte HMAC
 185
 172186                _encryptedDataSize = _totalStreamSize - headerSize - hmacSize;
 172187                _encryptedDataRemaining = _encryptedDataSize;
 188
 172189                if (_encryptedDataSize < 0)
 0190                {
 0191                    throw new InvalidDataException(SR.InvalidWinZipSize);
 192                }
 172193            }
 194
 344195            _hmac = IncrementalHash.CreateHMAC(HashAlgorithmName.SHA1, keyMaterial.HmacKey);
 344196            _aes.SetKey(keyMaterial.EncryptionKey);
 344197        }
 198
 199        // Compute and check the HMAC for the entire stream. This is called at the end of the stream, after all data has
 200        // similarly to how CRC is computed for non-encrypted ZIP entries. The HMAC is stored in the last 10 bytes of th
 201        private unsafe void FinalizeAndCompareHMAC(byte[] storedAuth)
 172202        {
 203
 172204            Debug.Assert(_hmac is not null, "HMAC should have been initialized");
 205
 206            // Finalize HMAC computation after reading, so we can use stackalloc
 172207            Span<byte> expectedAuth = stackalloc byte[SHA1.HashSizeInBytes];
 172208            if (!_hmac.TryGetHashAndReset(expectedAuth, out int bytesWritten) || bytesWritten < 10)
 0209            {
 0210                throw new InvalidDataException(SR.WinZipAuthCodeMismatch);
 211            }
 212
 213            // Compare the 10 bytes of the expected hash
 172214            Debug.Assert(storedAuth.Length == 10);
 172215            if (!CryptographicOperations.FixedTimeEquals(storedAuth, expectedAuth.Slice(0, storedAuth.Length)))
 0216            {
 0217                throw new InvalidDataException(SR.WinZipAuthCodeMismatch);
 218            }
 172219        }
 220
 221        private void ValidateAuthCode()
 172222        {
 172223            Debug.Assert(!_encrypting, "ValidateAuthCode should only be called during decryption.");
 224
 172225            if (_authCodeFinalized)
 86226            {
 86227                return;
 228            }
 229
 230            // Read the 10-byte stored authentication code from the stream
 86231            byte[] storedAuth = new byte[10];
 86232            _baseStream.ReadExactly(storedAuth);
 86233            FinalizeAndCompareHMAC(storedAuth);
 86234            _authCodeFinalized = true;
 172235        }
 236
 237        private async Task ValidateAuthCodeAsync(CancellationToken cancellationToken)
 172238        {
 172239            Debug.Assert(!_encrypting, "ValidateAuthCode should only be called during decryption.");
 240
 172241            if (_authCodeFinalized)
 86242            {
 86243                return;
 244            }
 245
 246            // Read the 10-byte stored authentication code from the stream
 86247            byte[] storedAuth = new byte[10];
 86248            await _baseStream.ReadExactlyAsync(storedAuth, cancellationToken).ConfigureAwait(false);
 86249            FinalizeAndCompareHMAC(storedAuth);
 86250            _authCodeFinalized = true;
 172251        }
 252
 253        private async Task WriteHeaderAsync(CancellationToken cancellationToken)
 86254        {
 86255            Debug.Assert(!_headerWritten);
 256
 86257            await _baseStream.WriteAsync(_salt, cancellationToken).ConfigureAwait(false);
 86258            await _baseStream.WriteAsync(_passwordVerifier, cancellationToken).ConfigureAwait(false);
 259
 86260            _headerWritten = true;
 86261        }
 262
 263        private void WriteHeader()
 86264        {
 86265            Debug.Assert(!_headerWritten);
 266
 86267            _baseStream.Write(_salt);
 86268            _baseStream.Write(_passwordVerifier);
 86269            _headerWritten = true;
 86270        }
 271
 272        private void ProcessBlock(Span<byte> buffer)
 344273        {
 344274            Debug.Assert(_hmac is not null, "HMAC should have been initialized");
 275
 688276            while (!buffer.IsEmpty)
 344277            {
 278                // Ensure we have enough keystream bytes available
 344279                int keystreamAvailable = KeystreamBufferSize - _keystreamOffset;
 344280                if (keystreamAvailable == 0)
 344281                {
 344282                    GenerateKeystreamBuffer();
 344283                    keystreamAvailable = KeystreamBufferSize;
 344284                }
 285
 286                // Process as many bytes as possible with the available keystream
 344287                int bytesToProcess = Math.Min(buffer.Length, keystreamAvailable);
 288
 344289                Span<byte> dataSpan = buffer.Slice(0, bytesToProcess);
 344290                ReadOnlySpan<byte> keystreamSpan = _keystreamBuffer.AsSpan(_keystreamOffset, bytesToProcess);
 291
 344292                if (_encrypting)
 172293                {
 294                    // For encryption: XOR first, then HMAC the ciphertext
 172295                    XorBytes(dataSpan, keystreamSpan);
 172296                    _hmac.AppendData(dataSpan);
 172297                }
 298                else
 172299                {
 300                    // For decryption: HMAC first (on ciphertext), then XOR
 172301                    _hmac.AppendData(dataSpan);
 172302                    XorBytes(dataSpan, keystreamSpan);
 172303                }
 304
 344305                _keystreamOffset += bytesToProcess;
 344306                buffer = buffer.Slice(bytesToProcess);
 344307            }
 344308        }
 309
 310        private void GenerateKeystreamBuffer()
 344311        {
 312            // Fill the buffer with all counter values first
 176816313            for (int i = 0; i < KeystreamBufferSize; i += BlockSize)
 88064314            {
 88064315                BinaryPrimitives.WriteUInt128LittleEndian(_keystreamBuffer.AsSpan(i, BlockSize), _counter);
 88064316                _counter++;
 88064317            }
 318
 319            // Encrypt all 256 counter blocks in a single call
 344320            _aes.EncryptEcb(_keystreamBuffer, _keystreamBuffer, PaddingMode.None);
 321
 344322            _keystreamOffset = 0;
 344323        }
 324
 325        private static void XorBytes(Span<byte> dest, ReadOnlySpan<byte> src)
 344326        {
 344327            Debug.Assert(dest.Length <= src.Length);
 328
 26984329            for (int i = 0; i < dest.Length; i++)
 13148330            {
 13148331                dest[i] ^= src[i];
 13148332            }
 344333        }
 334
 335        private async Task WriteAuthCodeCoreAsync(bool isAsync, CancellationToken cancellationToken)
 172336        {
 172337            Debug.Assert(_encrypting, "WriteAuthCode should only be called during encryption.");
 172338            Debug.Assert(_hmac is not null, "HMAC should have been initialized");
 339
 172340            if (_authCodeFinalized)
 0341            {
 0342                return;
 343            }
 344
 345            // WinZip AES spec requires only the first 10 bytes of the HMAC
 346            const int MacSizeInBytes = 10;
 347
 172348            byte[] authCode = new byte[SHA1.HashSizeInBytes];
 349
 172350            if (!_hmac.TryGetHashAndReset(authCode, out int bytesWritten) || bytesWritten < MacSizeInBytes)
 0351            {
 0352                throw new CryptographicException();
 353            }
 172354            if (isAsync)
 86355            {
 356                // WriteAsync requires Memory<byte>, so we must copy to a heap buffer for the async path
 86357                await _baseStream.WriteAsync(authCode.AsMemory(0, MacSizeInBytes), cancellationToken).ConfigureAwait(fal
 86358            }
 359            else
 86360            {
 86361                _baseStream.Write(authCode.AsSpan(0, MacSizeInBytes));
 86362            }
 363
 172364            _authCodeFinalized = true;
 172365        }
 366
 367        private void ThrowIfNotReadable()
 344368        {
 344369            ObjectDisposedException.ThrowIf(_disposed, this);
 370
 344371            if (_encrypting)
 0372            {
 0373                throw new NotSupportedException(SR.ReadingNotSupported);
 374            }
 344375        }
 376
 377        private int GetBytesToRead(int requestedCount)
 344378        {
 344379            if (_encryptedDataRemaining <= 0)
 172380            {
 172381                return 0;
 382            }
 383
 172384            return (int)Math.Min(requestedCount, _encryptedDataRemaining);
 344385        }
 386
 387        public override int Read(byte[] buffer, int offset, int count)
 172388        {
 172389            ValidateBufferArguments(buffer, offset, count);
 172390            return Read(buffer.AsSpan(offset, count));
 172391        }
 392
 393        public override int Read(Span<byte> buffer)
 172394        {
 172395            ThrowIfNotReadable();
 396
 172397            int bytesToRead = GetBytesToRead(buffer.Length);
 172398            if (bytesToRead == 0)
 86399            {
 400                // Only validate auth code when we've actually reached end of encrypted data,
 401                // not when caller simply requested 0 bytes
 86402                if (_encryptedDataRemaining <= 0)
 86403                {
 86404                    ValidateAuthCode();
 86405                }
 86406                return 0;
 407            }
 408
 86409            Span<byte> readBuffer = buffer.Slice(0, bytesToRead);
 86410            int bytesRead = _baseStream.Read(readBuffer);
 411
 86412            if (bytesRead > 0)
 86413            {
 86414                _encryptedDataRemaining -= bytesRead;
 86415                ProcessBlock(readBuffer.Slice(0, bytesRead));
 416
 417                // Validate auth code immediately when we've read all encrypted data
 86418                if (_encryptedDataRemaining <= 0)
 86419                {
 86420                    ValidateAuthCode();
 86421                }
 86422            }
 0423            else if (_encryptedDataRemaining > 0)
 0424            {
 425                // Base stream returned 0 bytes but we expected more encrypted data - stream is truncated
 0426                throw new InvalidDataException(SR.UnexpectedEndOfStream);
 427            }
 428
 86429            return bytesRead;
 172430        }
 431
 432        public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
 0433        {
 0434            ValidateBufferArguments(buffer, offset, count);
 0435            return ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
 0436        }
 437
 438        public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = defaul
 172439        {
 172440            cancellationToken.ThrowIfCancellationRequested();
 172441            ThrowIfNotReadable();
 442
 172443            int bytesToRead = GetBytesToRead(buffer.Length);
 172444            if (bytesToRead == 0)
 86445            {
 446                // Only validate auth code when we've actually reached end of encrypted data,
 447                // not when caller simply requested 0 bytes
 86448                if (_encryptedDataRemaining <= 0)
 86449                {
 86450                    await ValidateAuthCodeAsync(cancellationToken).ConfigureAwait(false);
 86451                }
 86452                return 0;
 453            }
 454
 86455            int bytesRead = await _baseStream.ReadAsync(buffer.Slice(0, bytesToRead), cancellationToken).ConfigureAwait(
 456
 86457            if (bytesRead > 0)
 86458            {
 86459                _encryptedDataRemaining -= bytesRead;
 86460                ProcessBlock(buffer.Span.Slice(0, bytesRead));
 461
 462                // Validate auth code immediately when we've read all encrypted data
 86463                if (_encryptedDataRemaining <= 0)
 86464                {
 86465                    await ValidateAuthCodeAsync(cancellationToken).ConfigureAwait(false);
 86466                }
 86467            }
 0468            else if (_encryptedDataRemaining > 0)
 0469            {
 470                // Base stream returned 0 bytes but we expected more encrypted data - stream is truncated
 0471                throw new InvalidDataException(SR.UnexpectedEndOfStream);
 472            }
 473
 86474            return bytesRead;
 172475        }
 476
 172477        private byte[] GetWriteWorkBuffer() => _writeWorkBuffer ??= new byte[KeystreamBufferSize];
 478
 479        private void WriteCore(ReadOnlySpan<byte> buffer, byte[] workBuffer)
 86480        {
 172481            while (!buffer.IsEmpty)
 86482            {
 86483                int bytesToProcess = Math.Min(buffer.Length, workBuffer.Length);
 484
 86485                buffer[..bytesToProcess].CopyTo(workBuffer);
 86486                ProcessBlock(workBuffer.AsSpan(0, bytesToProcess));
 86487                _baseStream.Write(workBuffer, 0, bytesToProcess);
 488
 86489                buffer = buffer[bytesToProcess..];
 86490            }
 86491        }
 492
 493        private void ThrowIfNotWritable()
 172494        {
 172495            ObjectDisposedException.ThrowIf(_disposed, this);
 496
 172497            if (!_encrypting)
 0498            {
 0499                throw new NotSupportedException(SR.WritingNotSupported);
 500            }
 172501        }
 502
 503        public override void Write(byte[] buffer, int offset, int count)
 86504        {
 86505            ValidateBufferArguments(buffer, offset, count);
 86506            Write(buffer.AsSpan(offset, count));
 86507        }
 508
 509        public override void Write(ReadOnlySpan<byte> buffer)
 86510        {
 86511            ThrowIfNotWritable();
 86512            if (!_headerWritten)
 86513            {
 86514                WriteHeader();
 86515            }
 516
 86517            WriteCore(buffer, GetWriteWorkBuffer());
 86518        }
 519
 520        public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
 0521        {
 0522            ValidateBufferArguments(buffer, offset, count);
 0523            return WriteAsyncCore(buffer.AsMemory(offset, count), cancellationToken).AsTask();
 0524        }
 525
 526        private async ValueTask WriteAsyncCore(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken)
 86527        {
 86528            cancellationToken.ThrowIfCancellationRequested();
 86529            ThrowIfNotWritable();
 86530            if (!_headerWritten)
 86531            {
 86532                await WriteHeaderAsync(cancellationToken).ConfigureAwait(false);
 86533            }
 534
 86535            byte[] workBuffer = GetWriteWorkBuffer();
 536
 172537            while (!buffer.IsEmpty)
 86538            {
 86539                int bytesToProcess = Math.Min(buffer.Length, workBuffer.Length);
 540
 86541                buffer[..bytesToProcess].CopyTo(workBuffer);
 86542                ProcessBlock(workBuffer.AsSpan(0, bytesToProcess));
 86543                await _baseStream.WriteAsync(workBuffer.AsMemory(0, bytesToProcess), cancellationToken).ConfigureAwait(f
 544
 86545                buffer = buffer[bytesToProcess..];
 86546            }
 86547        }
 548
 549        public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
 86550        {
 86551            return WriteAsyncCore(buffer, cancellationToken);
 86552        }
 553
 554        protected override void Dispose(bool disposing)
 172555        {
 172556            if (_disposed)
 0557            {
 0558                return;
 559            }
 560
 172561            if (disposing)
 172562            {
 563                try
 172564                {
 172565                    if (_encrypting && !_authCodeFinalized)
 86566                    {
 86567                        FinishEncryptingAsync(isAsync: false, CancellationToken.None).GetAwaiter().GetResult();
 86568                    }
 172569                }
 570                finally
 172571                {
 172572                    _disposed = true;
 172573                    _aes.Dispose();
 172574                    _hmac?.Dispose();
 575
 172576                    if (!_leaveOpen)
 86577                    {
 86578                        _baseStream.Dispose();
 86579                    }
 172580                }
 172581            }
 582
 172583            base.Dispose(disposing);
 172584        }
 585
 586        public override async ValueTask DisposeAsync()
 172587        {
 172588            if (_disposed)
 0589            {
 0590                return;
 591            }
 592
 593            try
 172594            {
 172595                if (_encrypting && !_authCodeFinalized)
 86596                {
 86597                    await FinishEncryptingAsync(isAsync: true, CancellationToken.None).ConfigureAwait(false);
 86598                }
 172599            }
 600            finally
 172601            {
 172602                _aes.Dispose();
 172603                _hmac?.Dispose();
 604
 172605                if (!_leaveOpen)
 86606                {
 86607                    await _baseStream.DisposeAsync().ConfigureAwait(false);
 86608                }
 172609            }
 610
 172611            _disposed = true;
 172612        }
 613
 614        /// <summary>
 615        /// Completes the encryption sequence: ensures the header is written (even for empty entries),
 616        /// appends the HMAC authentication code, and flushes the base stream.
 617        /// </summary>
 618        private async Task FinishEncryptingAsync(bool isAsync, CancellationToken cancellationToken)
 172619        {
 172620            Debug.Assert(_encrypting && !_authCodeFinalized);
 621
 622            // Ensure header is written even for empty files
 172623            if (!_headerWritten)
 0624            {
 0625                if (isAsync)
 0626                {
 0627                    await WriteHeaderAsync(cancellationToken).ConfigureAwait(false);
 0628                }
 629                else
 0630                {
 0631                    WriteHeader();
 0632                }
 0633            }
 634
 635            // Write Auth Code
 172636            await WriteAuthCodeCoreAsync(isAsync, cancellationToken).ConfigureAwait(false);
 637
 172638            if (isAsync)
 86639            {
 86640                await _baseStream.FlushAsync(cancellationToken).ConfigureAwait(false);
 86641            }
 642            else
 86643            {
 86644                _baseStream.Flush();
 86645            }
 172646        }
 647
 516648        public override bool CanRead => !_encrypting && !_disposed;
 172649        public override bool CanSeek => false;
 172650        public override bool CanWrite => _encrypting && !_disposed;
 0651        public override long Length => throw new NotSupportedException();
 652
 653        public override long Position
 654        {
 0655            get => throw new NotSupportedException();
 0656            set => throw new NotSupportedException();
 657        }
 658
 659        public override void Flush()
 0660        {
 0661            ObjectDisposedException.ThrowIf(_disposed, this);
 0662            _baseStream.Flush();
 0663        }
 664
 665        public override async Task FlushAsync(CancellationToken cancellationToken)
 0666        {
 0667            ObjectDisposedException.ThrowIf(_disposed, this);
 0668            await _baseStream.FlushAsync(cancellationToken).ConfigureAwait(false);
 0669        }
 670
 0671        public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
 0672        public override void SetLength(long value) => throw new NotSupportedException();
 673    }
 674}

Methods/Properties

.ctor(System.IO.Stream,System.IO.Compression.WinZipAesKeyMaterial,System.Int64,System.Boolean,System.Boolean)
GetSaltSize(System.Int32)
CreateKey(System.ReadOnlySpan`1<System.Char>,System.Byte[],System.Int32)
Create(System.IO.Stream,System.IO.Compression.WinZipAesKeyMaterial,System.Int64,System.Boolean,System.Boolean)
CreateAsync(System.IO.Stream,System.IO.Compression.WinZipAesKeyMaterial,System.Int64,System.Boolean,System.Boolean,System.Threading.CancellationToken)
ReadAndValidateHeaderCore(System.Boolean,System.IO.Stream,System.IO.Compression.WinZipAesKeyMaterial,System.Threading.CancellationToken)
FinalizeAndCompareHMAC(System.Byte[])
ValidateAuthCode()
ValidateAuthCodeAsync(System.Threading.CancellationToken)
WriteHeaderAsync(System.Threading.CancellationToken)
WriteHeader()
ProcessBlock(System.Span`1<System.Byte>)
GenerateKeystreamBuffer()
XorBytes(System.Span`1<System.Byte>,System.ReadOnlySpan`1<System.Byte>)
WriteAuthCodeCoreAsync(System.Boolean,System.Threading.CancellationToken)
ThrowIfNotReadable()
GetBytesToRead(System.Int32)
Read(System.Byte[],System.Int32,System.Int32)
Read(System.Span`1<System.Byte>)
ReadAsync(System.Byte[],System.Int32,System.Int32,System.Threading.CancellationToken)
ReadAsync(System.Memory`1<System.Byte>,System.Threading.CancellationToken)
GetWriteWorkBuffer()
WriteCore(System.ReadOnlySpan`1<System.Byte>,System.Byte[])
ThrowIfNotWritable()
Write(System.Byte[],System.Int32,System.Int32)
Write(System.ReadOnlySpan`1<System.Byte>)
WriteAsync(System.Byte[],System.Int32,System.Int32,System.Threading.CancellationToken)
WriteAsyncCore(System.ReadOnlyMemory`1<System.Byte>,System.Threading.CancellationToken)
WriteAsync(System.ReadOnlyMemory`1<System.Byte>,System.Threading.CancellationToken)
Dispose(System.Boolean)
DisposeAsync()
FinishEncryptingAsync(System.Boolean,System.Threading.CancellationToken)
CanRead()
CanSeek()
CanWrite()
Length()
Position()
Position(System.Int64)
Flush()
FlushAsync(System.Threading.CancellationToken)
Seek(System.Int64,System.IO.SeekOrigin)
SetLength(System.Int64)