< 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;
 39623        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
 39636        private readonly byte[] _keystreamBuffer = new byte[KeystreamBufferSize];
 39637        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)
 19843        {
 19844            if (OperatingSystem.IsBrowser())
 045            {
 046                throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnBrowser);
 47            }
 48
 19849            return WinZipAesKeyMaterial.GetSaltSize(keySizeBits);
 19850        }
 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)
 59456        {
 59457            if (OperatingSystem.IsBrowser())
 058            {
 059                throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnBrowser);
 60            }
 59461            return WinZipAesKeyMaterial.Create(password, salt, keySizeBits);
 59462        }
 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
 39668        {
 39669            if (OperatingSystem.IsBrowser())
 070            {
 071                throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnBrowser);
 72            }
 73
 39674            ArgumentNullException.ThrowIfNull(baseStream);
 75
 39676            if (!encrypting)
 19877            {
 19878                ReadAndValidateHeaderCore(isAsync: false, baseStream, keyMaterial, CancellationToken.None).GetAwaiter().
 9979            }
 80
 29781            return new WinZipAesStream(baseStream, keyMaterial, totalStreamSize, encrypting, leaveOpen);
 29782        }
 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
 19888        {
 19889            if (OperatingSystem.IsBrowser())
 090            {
 091                throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnBrowser);
 92            }
 93
 19894            ArgumentNullException.ThrowIfNull(baseStream);
 95
 19896            if (!encrypting)
 19897            {
 19898                await ReadAndValidateHeaderCore(isAsync: true, baseStream, keyMaterial, cancellationToken).ConfigureAwai
 9999            }
 100
 99101            return new WinZipAesStream(baseStream, keyMaterial, totalStreamSize, encrypting, leaveOpen);
 99102        }
 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
 396108        {
 396109            if (OperatingSystem.IsBrowser())
 0110            {
 0111                throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnBrowser);
 112            }
 396113            int saltSize = keyMaterial.SaltSize;
 114
 115            // Read salt from stream
 396116            byte[] fileSalt = new byte[saltSize];
 396117            if (isAsync)
 198118            {
 198119                await baseStream.ReadExactlyAsync(fileSalt, cancellationToken).ConfigureAwait(false);
 198120            }
 121            else
 198122            {
 198123                baseStream.ReadExactly(fileSalt);
 198124            }
 125
 126            // Read the 2-byte password verifier from stream
 396127            byte[] verifier = new byte[2];
 396128            if (isAsync)
 198129            {
 198130                await baseStream.ReadExactlyAsync(verifier, cancellationToken).ConfigureAwait(false);
 198131            }
 132            else
 198133            {
 198134                baseStream.ReadExactly(verifier);
 198135            }
 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.
 396139            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.
 396146            if (!CryptographicOperations.FixedTimeEquals(verifier, keyMaterial.PasswordVerifier))
 198147            {
 198148                throw new InvalidDataException(SR.InvalidPassword);
 149            }
 198150        }
 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>
 396156        private WinZipAesStream(Stream baseStream, WinZipAesKeyMaterial keyMaterial, long totalStreamSize, bool encrypti
 396157        {
 396158            if (OperatingSystem.IsBrowser())
 0159            {
 0160                throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnBrowser);
 161            }
 162
 396163            _baseStream = baseStream;
 164
 396165            Debug.Assert((totalStreamSize >= 0) == !encrypting, "Total stream size must be known when decrypting");
 166
 396167            _encrypting = encrypting;
 396168            _totalStreamSize = totalStreamSize;
 396169            _leaveOpen = leaveOpen;
 170
 396171            _aes = Aes.Create();
 172
 396173            _salt = keyMaterial.Salt;
 396174            _passwordVerifier = keyMaterial.PasswordVerifier;
 175
 396176            if (encrypting)
 198177            {
 198178                _encryptedDataSize = -1;
 198179                _encryptedDataRemaining = -1;
 198180            }
 181            else
 198182            {
 198183                int headerSize = checked(keyMaterial.SaltSize + 2); // Salt + Password Verifier
 184                const int hmacSize = 10; // 10-byte HMAC
 185
 198186                _encryptedDataSize = _totalStreamSize - headerSize - hmacSize;
 198187                _encryptedDataRemaining = _encryptedDataSize;
 188
 198189                if (_encryptedDataSize < 0)
 0190                {
 0191                    throw new InvalidDataException(SR.InvalidWinZipSize);
 192                }
 198193            }
 194
 396195            _hmac = IncrementalHash.CreateHMAC(HashAlgorithmName.SHA1, keyMaterial.HmacKey);
 396196            _aes.SetKey(keyMaterial.EncryptionKey);
 396197        }
 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)
 198202        {
 203
 198204            Debug.Assert(_hmac is not null, "HMAC should have been initialized");
 205
 206            // Finalize HMAC computation after reading, so we can use stackalloc
 198207            Span<byte> expectedAuth = stackalloc byte[SHA1.HashSizeInBytes];
 198208            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
 198214            Debug.Assert(storedAuth.Length == 10);
 198215            if (!CryptographicOperations.FixedTimeEquals(storedAuth, expectedAuth.Slice(0, storedAuth.Length)))
 0216            {
 0217                throw new InvalidDataException(SR.WinZipAuthCodeMismatch);
 218            }
 198219        }
 220
 221        private void ValidateAuthCode()
 198222        {
 198223            Debug.Assert(!_encrypting, "ValidateAuthCode should only be called during decryption.");
 224
 198225            if (_authCodeFinalized)
 99226            {
 99227                return;
 228            }
 229
 230            // Read the 10-byte stored authentication code from the stream
 99231            byte[] storedAuth = new byte[10];
 99232            _baseStream.ReadExactly(storedAuth);
 99233            FinalizeAndCompareHMAC(storedAuth);
 99234            _authCodeFinalized = true;
 198235        }
 236
 237        private async Task ValidateAuthCodeAsync(CancellationToken cancellationToken)
 198238        {
 198239            Debug.Assert(!_encrypting, "ValidateAuthCode should only be called during decryption.");
 240
 198241            if (_authCodeFinalized)
 99242            {
 99243                return;
 244            }
 245
 246            // Read the 10-byte stored authentication code from the stream
 99247            byte[] storedAuth = new byte[10];
 99248            await _baseStream.ReadExactlyAsync(storedAuth, cancellationToken).ConfigureAwait(false);
 99249            FinalizeAndCompareHMAC(storedAuth);
 99250            _authCodeFinalized = true;
 198251        }
 252
 253        private async Task WriteHeaderAsync(CancellationToken cancellationToken)
 99254        {
 99255            Debug.Assert(!_headerWritten);
 256
 99257            await _baseStream.WriteAsync(_salt, cancellationToken).ConfigureAwait(false);
 99258            await _baseStream.WriteAsync(_passwordVerifier, cancellationToken).ConfigureAwait(false);
 259
 99260            _headerWritten = true;
 99261        }
 262
 263        private void WriteHeader()
 99264        {
 99265            Debug.Assert(!_headerWritten);
 266
 99267            _baseStream.Write(_salt);
 99268            _baseStream.Write(_passwordVerifier);
 99269            _headerWritten = true;
 99270        }
 271
 272        private void ProcessBlock(Span<byte> buffer)
 396273        {
 396274            Debug.Assert(_hmac is not null, "HMAC should have been initialized");
 275
 792276            while (!buffer.IsEmpty)
 396277            {
 278                // Ensure we have enough keystream bytes available
 396279                int keystreamAvailable = KeystreamBufferSize - _keystreamOffset;
 396280                if (keystreamAvailable == 0)
 396281                {
 396282                    GenerateKeystreamBuffer();
 396283                    keystreamAvailable = KeystreamBufferSize;
 396284                }
 285
 286                // Process as many bytes as possible with the available keystream
 396287                int bytesToProcess = Math.Min(buffer.Length, keystreamAvailable);
 288
 396289                Span<byte> dataSpan = buffer.Slice(0, bytesToProcess);
 396290                ReadOnlySpan<byte> keystreamSpan = _keystreamBuffer.AsSpan(_keystreamOffset, bytesToProcess);
 291
 396292                if (_encrypting)
 198293                {
 294                    // For encryption: XOR first, then HMAC the ciphertext
 198295                    XorBytes(dataSpan, keystreamSpan);
 198296                    _hmac.AppendData(dataSpan);
 198297                }
 298                else
 198299                {
 300                    // For decryption: HMAC first (on ciphertext), then XOR
 198301                    _hmac.AppendData(dataSpan);
 198302                    XorBytes(dataSpan, keystreamSpan);
 198303                }
 304
 396305                _keystreamOffset += bytesToProcess;
 396306                buffer = buffer.Slice(bytesToProcess);
 396307            }
 396308        }
 309
 310        private void GenerateKeystreamBuffer()
 396311        {
 312            // Fill the buffer with all counter values first
 203544313            for (int i = 0; i < KeystreamBufferSize; i += BlockSize)
 101376314            {
 101376315                BinaryPrimitives.WriteUInt128LittleEndian(_keystreamBuffer.AsSpan(i, BlockSize), _counter);
 101376316                _counter++;
 101376317            }
 318
 319            // Encrypt all 256 counter blocks in a single call
 396320            _aes.EncryptEcb(_keystreamBuffer, _keystreamBuffer, PaddingMode.None);
 321
 396322            _keystreamOffset = 0;
 396323        }
 324
 325        private static void XorBytes(Span<byte> dest, ReadOnlySpan<byte> src)
 396326        {
 396327            Debug.Assert(dest.Length <= src.Length);
 328
 41856329            for (int i = 0; i < dest.Length; i++)
 20532330            {
 20532331                dest[i] ^= src[i];
 20532332            }
 396333        }
 334
 335        private async Task WriteAuthCodeCoreAsync(bool isAsync, CancellationToken cancellationToken)
 198336        {
 198337            Debug.Assert(_encrypting, "WriteAuthCode should only be called during encryption.");
 198338            Debug.Assert(_hmac is not null, "HMAC should have been initialized");
 339
 198340            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
 198348            byte[] authCode = new byte[SHA1.HashSizeInBytes];
 349
 198350            if (!_hmac.TryGetHashAndReset(authCode, out int bytesWritten) || bytesWritten < MacSizeInBytes)
 0351            {
 0352                throw new CryptographicException();
 353            }
 198354            if (isAsync)
 99355            {
 356                // WriteAsync requires Memory<byte>, so we must copy to a heap buffer for the async path
 99357                await _baseStream.WriteAsync(authCode.AsMemory(0, MacSizeInBytes), cancellationToken).ConfigureAwait(fal
 99358            }
 359            else
 99360            {
 99361                _baseStream.Write(authCode.AsSpan(0, MacSizeInBytes));
 99362            }
 363
 198364            _authCodeFinalized = true;
 198365        }
 366
 367        private void ThrowIfNotReadable()
 396368        {
 396369            ObjectDisposedException.ThrowIf(_disposed, this);
 370
 396371            if (_encrypting)
 0372            {
 0373                throw new NotSupportedException(SR.ReadingNotSupported);
 374            }
 396375        }
 376
 377        private int GetBytesToRead(int requestedCount)
 396378        {
 396379            if (_encryptedDataRemaining <= 0)
 198380            {
 198381                return 0;
 382            }
 383
 198384            return (int)Math.Min(requestedCount, _encryptedDataRemaining);
 396385        }
 386
 387        public override int Read(byte[] buffer, int offset, int count)
 198388        {
 198389            ValidateBufferArguments(buffer, offset, count);
 198390            return Read(buffer.AsSpan(offset, count));
 198391        }
 392
 393        public override int Read(Span<byte> buffer)
 198394        {
 198395            ThrowIfNotReadable();
 396
 198397            int bytesToRead = GetBytesToRead(buffer.Length);
 198398            if (bytesToRead == 0)
 99399            {
 400                // Only validate auth code when we've actually reached end of encrypted data,
 401                // not when caller simply requested 0 bytes
 99402                if (_encryptedDataRemaining <= 0)
 99403                {
 99404                    ValidateAuthCode();
 99405                }
 99406                return 0;
 407            }
 408
 99409            Span<byte> readBuffer = buffer.Slice(0, bytesToRead);
 99410            int bytesRead = _baseStream.Read(readBuffer);
 411
 99412            if (bytesRead > 0)
 99413            {
 99414                _encryptedDataRemaining -= bytesRead;
 99415                ProcessBlock(readBuffer.Slice(0, bytesRead));
 416
 417                // Validate auth code immediately when we've read all encrypted data
 99418                if (_encryptedDataRemaining <= 0)
 99419                {
 99420                    ValidateAuthCode();
 99421                }
 99422            }
 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
 99429            return bytesRead;
 198430        }
 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
 198439        {
 198440            cancellationToken.ThrowIfCancellationRequested();
 198441            ThrowIfNotReadable();
 442
 198443            int bytesToRead = GetBytesToRead(buffer.Length);
 198444            if (bytesToRead == 0)
 99445            {
 446                // Only validate auth code when we've actually reached end of encrypted data,
 447                // not when caller simply requested 0 bytes
 99448                if (_encryptedDataRemaining <= 0)
 99449                {
 99450                    await ValidateAuthCodeAsync(cancellationToken).ConfigureAwait(false);
 99451                }
 99452                return 0;
 453            }
 454
 99455            int bytesRead = await _baseStream.ReadAsync(buffer.Slice(0, bytesToRead), cancellationToken).ConfigureAwait(
 456
 99457            if (bytesRead > 0)
 99458            {
 99459                _encryptedDataRemaining -= bytesRead;
 99460                ProcessBlock(buffer.Span.Slice(0, bytesRead));
 461
 462                // Validate auth code immediately when we've read all encrypted data
 99463                if (_encryptedDataRemaining <= 0)
 99464                {
 99465                    await ValidateAuthCodeAsync(cancellationToken).ConfigureAwait(false);
 99466                }
 99467            }
 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
 99474            return bytesRead;
 198475        }
 476
 198477        private byte[] GetWriteWorkBuffer() => _writeWorkBuffer ??= new byte[KeystreamBufferSize];
 478
 479        private void WriteCore(ReadOnlySpan<byte> buffer, byte[] workBuffer)
 99480        {
 198481            while (!buffer.IsEmpty)
 99482            {
 99483                int bytesToProcess = Math.Min(buffer.Length, workBuffer.Length);
 484
 99485                buffer[..bytesToProcess].CopyTo(workBuffer);
 99486                ProcessBlock(workBuffer.AsSpan(0, bytesToProcess));
 99487                _baseStream.Write(workBuffer, 0, bytesToProcess);
 488
 99489                buffer = buffer[bytesToProcess..];
 99490            }
 99491        }
 492
 493        private void ThrowIfNotWritable()
 198494        {
 198495            ObjectDisposedException.ThrowIf(_disposed, this);
 496
 198497            if (!_encrypting)
 0498            {
 0499                throw new NotSupportedException(SR.WritingNotSupported);
 500            }
 198501        }
 502
 503        public override void Write(byte[] buffer, int offset, int count)
 99504        {
 99505            ValidateBufferArguments(buffer, offset, count);
 99506            Write(buffer.AsSpan(offset, count));
 99507        }
 508
 509        public override void Write(ReadOnlySpan<byte> buffer)
 99510        {
 99511            ThrowIfNotWritable();
 99512            if (!_headerWritten)
 99513            {
 99514                WriteHeader();
 99515            }
 516
 99517            WriteCore(buffer, GetWriteWorkBuffer());
 99518        }
 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)
 99527        {
 99528            cancellationToken.ThrowIfCancellationRequested();
 99529            ThrowIfNotWritable();
 99530            if (!_headerWritten)
 99531            {
 99532                await WriteHeaderAsync(cancellationToken).ConfigureAwait(false);
 99533            }
 534
 99535            byte[] workBuffer = GetWriteWorkBuffer();
 536
 198537            while (!buffer.IsEmpty)
 99538            {
 99539                int bytesToProcess = Math.Min(buffer.Length, workBuffer.Length);
 540
 99541                buffer[..bytesToProcess].CopyTo(workBuffer);
 99542                ProcessBlock(workBuffer.AsSpan(0, bytesToProcess));
 99543                await _baseStream.WriteAsync(workBuffer.AsMemory(0, bytesToProcess), cancellationToken).ConfigureAwait(f
 544
 99545                buffer = buffer[bytesToProcess..];
 99546            }
 99547        }
 548
 549        public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
 99550        {
 99551            return WriteAsyncCore(buffer, cancellationToken);
 99552        }
 553
 554        protected override void Dispose(bool disposing)
 198555        {
 198556            if (_disposed)
 0557            {
 0558                return;
 559            }
 560
 198561            if (disposing)
 198562            {
 563                try
 198564                {
 198565                    if (_encrypting && !_authCodeFinalized)
 99566                    {
 99567                        FinishEncryptingAsync(isAsync: false, CancellationToken.None).GetAwaiter().GetResult();
 99568                    }
 198569                }
 570                finally
 198571                {
 198572                    _disposed = true;
 198573                    _aes.Dispose();
 198574                    _hmac?.Dispose();
 575
 198576                    if (!_leaveOpen)
 99577                    {
 99578                        _baseStream.Dispose();
 99579                    }
 198580                }
 198581            }
 582
 198583            base.Dispose(disposing);
 198584        }
 585
 586        public override async ValueTask DisposeAsync()
 198587        {
 198588            if (_disposed)
 0589            {
 0590                return;
 591            }
 592
 593            try
 198594            {
 198595                if (_encrypting && !_authCodeFinalized)
 99596                {
 99597                    await FinishEncryptingAsync(isAsync: true, CancellationToken.None).ConfigureAwait(false);
 99598                }
 198599            }
 600            finally
 198601            {
 198602                _aes.Dispose();
 198603                _hmac?.Dispose();
 604
 198605                if (!_leaveOpen)
 99606                {
 99607                    await _baseStream.DisposeAsync().ConfigureAwait(false);
 99608                }
 198609            }
 610
 198611            _disposed = true;
 198612        }
 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)
 198619        {
 198620            Debug.Assert(_encrypting && !_authCodeFinalized);
 621
 622            // Ensure header is written even for empty files
 198623            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
 198636            await WriteAuthCodeCoreAsync(isAsync, cancellationToken).ConfigureAwait(false);
 637
 198638            if (isAsync)
 99639            {
 99640                await _baseStream.FlushAsync(cancellationToken).ConfigureAwait(false);
 99641            }
 642            else
 99643            {
 99644                _baseStream.Flush();
 99645            }
 198646        }
 647
 594648        public override bool CanRead => !_encrypting && !_disposed;
 198649        public override bool CanSeek => false;
 198650        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)