< 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;
 18823        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
 18836        private readonly byte[] _keystreamBuffer = new byte[KeystreamBufferSize];
 18837        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)
 9443        {
 9444            if (OperatingSystem.IsBrowser())
 045            {
 046                throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnBrowser);
 47            }
 48
 9449            return WinZipAesKeyMaterial.GetSaltSize(keySizeBits);
 9450        }
 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)
 28256        {
 28257            if (OperatingSystem.IsBrowser())
 058            {
 059                throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnBrowser);
 60            }
 28261            return WinZipAesKeyMaterial.Create(password, salt, keySizeBits);
 28262        }
 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
 18868        {
 18869            if (OperatingSystem.IsBrowser())
 070            {
 071                throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnBrowser);
 72            }
 73
 18874            ArgumentNullException.ThrowIfNull(baseStream);
 75
 18876            if (!encrypting)
 9477            {
 9478                ReadAndValidateHeaderCore(isAsync: false, baseStream, keyMaterial, CancellationToken.None).GetAwaiter().
 4779            }
 80
 14181            return new WinZipAesStream(baseStream, keyMaterial, totalStreamSize, encrypting, leaveOpen);
 14182        }
 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
 9488        {
 9489            if (OperatingSystem.IsBrowser())
 090            {
 091                throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnBrowser);
 92            }
 93
 9494            ArgumentNullException.ThrowIfNull(baseStream);
 95
 9496            if (!encrypting)
 9497            {
 9498                await ReadAndValidateHeaderCore(isAsync: true, baseStream, keyMaterial, cancellationToken).ConfigureAwai
 4799            }
 100
 47101            return new WinZipAesStream(baseStream, keyMaterial, totalStreamSize, encrypting, leaveOpen);
 47102        }
 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
 188108        {
 188109            if (OperatingSystem.IsBrowser())
 0110            {
 0111                throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnBrowser);
 112            }
 188113            int saltSize = keyMaterial.SaltSize;
 114
 115            // Read salt from stream
 188116            byte[] fileSalt = new byte[saltSize];
 188117            if (isAsync)
 94118            {
 94119                await baseStream.ReadExactlyAsync(fileSalt, cancellationToken).ConfigureAwait(false);
 94120            }
 121            else
 94122            {
 94123                baseStream.ReadExactly(fileSalt);
 94124            }
 125
 126            // Read the 2-byte password verifier from stream
 188127            byte[] verifier = new byte[2];
 188128            if (isAsync)
 94129            {
 94130                await baseStream.ReadExactlyAsync(verifier, cancellationToken).ConfigureAwait(false);
 94131            }
 132            else
 94133            {
 94134                baseStream.ReadExactly(verifier);
 94135            }
 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.
 188139            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.
 188146            if (!CryptographicOperations.FixedTimeEquals(verifier, keyMaterial.PasswordVerifier))
 94147            {
 94148                throw new InvalidDataException(SR.InvalidPassword);
 149            }
 94150        }
 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>
 188156        private WinZipAesStream(Stream baseStream, WinZipAesKeyMaterial keyMaterial, long totalStreamSize, bool encrypti
 188157        {
 188158            if (OperatingSystem.IsBrowser())
 0159            {
 0160                throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnBrowser);
 161            }
 162
 188163            _baseStream = baseStream;
 164
 188165            Debug.Assert((totalStreamSize >= 0) == !encrypting, "Total stream size must be known when decrypting");
 166
 188167            _encrypting = encrypting;
 188168            _totalStreamSize = totalStreamSize;
 188169            _leaveOpen = leaveOpen;
 170
 188171            _aes = Aes.Create();
 172
 188173            _salt = keyMaterial.Salt;
 188174            _passwordVerifier = keyMaterial.PasswordVerifier;
 175
 188176            if (encrypting)
 94177            {
 94178                _encryptedDataSize = -1;
 94179                _encryptedDataRemaining = -1;
 94180            }
 181            else
 94182            {
 94183                int headerSize = checked(keyMaterial.SaltSize + 2); // Salt + Password Verifier
 184                const int hmacSize = 10; // 10-byte HMAC
 185
 94186                _encryptedDataSize = _totalStreamSize - headerSize - hmacSize;
 94187                _encryptedDataRemaining = _encryptedDataSize;
 188
 94189                if (_encryptedDataSize < 0)
 0190                {
 0191                    throw new InvalidDataException(SR.InvalidWinZipSize);
 192                }
 94193            }
 194
 188195            _hmac = IncrementalHash.CreateHMAC(HashAlgorithmName.SHA1, keyMaterial.HmacKey);
 188196            _aes.SetKey(keyMaterial.EncryptionKey);
 188197        }
 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)
 94202        {
 203
 94204            Debug.Assert(_hmac is not null, "HMAC should have been initialized");
 205
 206            // Finalize HMAC computation after reading, so we can use stackalloc
 94207            Span<byte> expectedAuth = stackalloc byte[SHA1.HashSizeInBytes];
 94208            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
 94214            Debug.Assert(storedAuth.Length == 10);
 94215            if (!CryptographicOperations.FixedTimeEquals(storedAuth, expectedAuth.Slice(0, storedAuth.Length)))
 0216            {
 0217                throw new InvalidDataException(SR.WinZipAuthCodeMismatch);
 218            }
 94219        }
 220
 221        private void ValidateAuthCode()
 94222        {
 94223            Debug.Assert(!_encrypting, "ValidateAuthCode should only be called during decryption.");
 224
 94225            if (_authCodeFinalized)
 47226            {
 47227                return;
 228            }
 229
 230            // Read the 10-byte stored authentication code from the stream
 47231            byte[] storedAuth = new byte[10];
 47232            _baseStream.ReadExactly(storedAuth);
 47233            FinalizeAndCompareHMAC(storedAuth);
 47234            _authCodeFinalized = true;
 94235        }
 236
 237        private async Task ValidateAuthCodeAsync(CancellationToken cancellationToken)
 94238        {
 94239            Debug.Assert(!_encrypting, "ValidateAuthCode should only be called during decryption.");
 240
 94241            if (_authCodeFinalized)
 47242            {
 47243                return;
 244            }
 245
 246            // Read the 10-byte stored authentication code from the stream
 47247            byte[] storedAuth = new byte[10];
 47248            await _baseStream.ReadExactlyAsync(storedAuth, cancellationToken).ConfigureAwait(false);
 47249            FinalizeAndCompareHMAC(storedAuth);
 47250            _authCodeFinalized = true;
 94251        }
 252
 253        private async Task WriteHeaderAsync(CancellationToken cancellationToken)
 47254        {
 47255            Debug.Assert(!_headerWritten);
 256
 47257            await _baseStream.WriteAsync(_salt, cancellationToken).ConfigureAwait(false);
 47258            await _baseStream.WriteAsync(_passwordVerifier, cancellationToken).ConfigureAwait(false);
 259
 47260            _headerWritten = true;
 47261        }
 262
 263        private void WriteHeader()
 47264        {
 47265            Debug.Assert(!_headerWritten);
 266
 47267            _baseStream.Write(_salt);
 47268            _baseStream.Write(_passwordVerifier);
 47269            _headerWritten = true;
 47270        }
 271
 272        private void ProcessBlock(Span<byte> buffer)
 188273        {
 188274            Debug.Assert(_hmac is not null, "HMAC should have been initialized");
 275
 376276            while (!buffer.IsEmpty)
 188277            {
 278                // Ensure we have enough keystream bytes available
 188279                int keystreamAvailable = KeystreamBufferSize - _keystreamOffset;
 188280                if (keystreamAvailable == 0)
 188281                {
 188282                    GenerateKeystreamBuffer();
 188283                    keystreamAvailable = KeystreamBufferSize;
 188284                }
 285
 286                // Process as many bytes as possible with the available keystream
 188287                int bytesToProcess = Math.Min(buffer.Length, keystreamAvailable);
 288
 188289                Span<byte> dataSpan = buffer.Slice(0, bytesToProcess);
 188290                ReadOnlySpan<byte> keystreamSpan = _keystreamBuffer.AsSpan(_keystreamOffset, bytesToProcess);
 291
 188292                if (_encrypting)
 94293                {
 294                    // For encryption: XOR first, then HMAC the ciphertext
 94295                    XorBytes(dataSpan, keystreamSpan);
 94296                    _hmac.AppendData(dataSpan);
 94297                }
 298                else
 94299                {
 300                    // For decryption: HMAC first (on ciphertext), then XOR
 94301                    _hmac.AppendData(dataSpan);
 94302                    XorBytes(dataSpan, keystreamSpan);
 94303                }
 304
 188305                _keystreamOffset += bytesToProcess;
 188306                buffer = buffer.Slice(bytesToProcess);
 188307            }
 188308        }
 309
 310        private void GenerateKeystreamBuffer()
 188311        {
 312            // Fill the buffer with all counter values first
 96632313            for (int i = 0; i < KeystreamBufferSize; i += BlockSize)
 48128314            {
 48128315                BinaryPrimitives.WriteUInt128LittleEndian(_keystreamBuffer.AsSpan(i, BlockSize), _counter);
 48128316                _counter++;
 48128317            }
 318
 319            // Encrypt all 256 counter blocks in a single call
 188320            _aes.EncryptEcb(_keystreamBuffer, _keystreamBuffer, PaddingMode.None);
 321
 188322            _keystreamOffset = 0;
 188323        }
 324
 325        private static void XorBytes(Span<byte> dest, ReadOnlySpan<byte> src)
 188326        {
 188327            Debug.Assert(dest.Length <= src.Length);
 328
 10968329            for (int i = 0; i < dest.Length; i++)
 5296330            {
 5296331                dest[i] ^= src[i];
 5296332            }
 188333        }
 334
 335        private async Task WriteAuthCodeCoreAsync(bool isAsync, CancellationToken cancellationToken)
 94336        {
 94337            Debug.Assert(_encrypting, "WriteAuthCode should only be called during encryption.");
 94338            Debug.Assert(_hmac is not null, "HMAC should have been initialized");
 339
 94340            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
 94348            byte[] authCode = new byte[SHA1.HashSizeInBytes];
 349
 94350            if (!_hmac.TryGetHashAndReset(authCode, out int bytesWritten) || bytesWritten < MacSizeInBytes)
 0351            {
 0352                throw new CryptographicException();
 353            }
 94354            if (isAsync)
 47355            {
 356                // WriteAsync requires Memory<byte>, so we must copy to a heap buffer for the async path
 47357                await _baseStream.WriteAsync(authCode.AsMemory(0, MacSizeInBytes), cancellationToken).ConfigureAwait(fal
 47358            }
 359            else
 47360            {
 47361                _baseStream.Write(authCode.AsSpan(0, MacSizeInBytes));
 47362            }
 363
 94364            _authCodeFinalized = true;
 94365        }
 366
 367        private void ThrowIfNotReadable()
 188368        {
 188369            ObjectDisposedException.ThrowIf(_disposed, this);
 370
 188371            if (_encrypting)
 0372            {
 0373                throw new NotSupportedException(SR.ReadingNotSupported);
 374            }
 188375        }
 376
 377        private int GetBytesToRead(int requestedCount)
 188378        {
 188379            if (_encryptedDataRemaining <= 0)
 94380            {
 94381                return 0;
 382            }
 383
 94384            return (int)Math.Min(requestedCount, _encryptedDataRemaining);
 188385        }
 386
 387        public override int Read(byte[] buffer, int offset, int count)
 94388        {
 94389            ValidateBufferArguments(buffer, offset, count);
 94390            return Read(buffer.AsSpan(offset, count));
 94391        }
 392
 393        public override int Read(Span<byte> buffer)
 94394        {
 94395            ThrowIfNotReadable();
 396
 94397            int bytesToRead = GetBytesToRead(buffer.Length);
 94398            if (bytesToRead == 0)
 47399            {
 400                // Only validate auth code when we've actually reached end of encrypted data,
 401                // not when caller simply requested 0 bytes
 47402                if (_encryptedDataRemaining <= 0)
 47403                {
 47404                    ValidateAuthCode();
 47405                }
 47406                return 0;
 407            }
 408
 47409            Span<byte> readBuffer = buffer.Slice(0, bytesToRead);
 47410            int bytesRead = _baseStream.Read(readBuffer);
 411
 47412            if (bytesRead > 0)
 47413            {
 47414                _encryptedDataRemaining -= bytesRead;
 47415                ProcessBlock(readBuffer.Slice(0, bytesRead));
 416
 417                // Validate auth code immediately when we've read all encrypted data
 47418                if (_encryptedDataRemaining <= 0)
 47419                {
 47420                    ValidateAuthCode();
 47421                }
 47422            }
 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
 47429            return bytesRead;
 94430        }
 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
 94439        {
 94440            cancellationToken.ThrowIfCancellationRequested();
 94441            ThrowIfNotReadable();
 442
 94443            int bytesToRead = GetBytesToRead(buffer.Length);
 94444            if (bytesToRead == 0)
 47445            {
 446                // Only validate auth code when we've actually reached end of encrypted data,
 447                // not when caller simply requested 0 bytes
 47448                if (_encryptedDataRemaining <= 0)
 47449                {
 47450                    await ValidateAuthCodeAsync(cancellationToken).ConfigureAwait(false);
 47451                }
 47452                return 0;
 453            }
 454
 47455            int bytesRead = await _baseStream.ReadAsync(buffer.Slice(0, bytesToRead), cancellationToken).ConfigureAwait(
 456
 47457            if (bytesRead > 0)
 47458            {
 47459                _encryptedDataRemaining -= bytesRead;
 47460                ProcessBlock(buffer.Span.Slice(0, bytesRead));
 461
 462                // Validate auth code immediately when we've read all encrypted data
 47463                if (_encryptedDataRemaining <= 0)
 47464                {
 47465                    await ValidateAuthCodeAsync(cancellationToken).ConfigureAwait(false);
 47466                }
 47467            }
 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
 47474            return bytesRead;
 94475        }
 476
 94477        private byte[] GetWriteWorkBuffer() => _writeWorkBuffer ??= new byte[KeystreamBufferSize];
 478
 479        private void WriteCore(ReadOnlySpan<byte> buffer, byte[] workBuffer)
 47480        {
 94481            while (!buffer.IsEmpty)
 47482            {
 47483                int bytesToProcess = Math.Min(buffer.Length, workBuffer.Length);
 484
 47485                buffer[..bytesToProcess].CopyTo(workBuffer);
 47486                ProcessBlock(workBuffer.AsSpan(0, bytesToProcess));
 47487                _baseStream.Write(workBuffer, 0, bytesToProcess);
 488
 47489                buffer = buffer[bytesToProcess..];
 47490            }
 47491        }
 492
 493        private void ThrowIfNotWritable()
 94494        {
 94495            ObjectDisposedException.ThrowIf(_disposed, this);
 496
 94497            if (!_encrypting)
 0498            {
 0499                throw new NotSupportedException(SR.WritingNotSupported);
 500            }
 94501        }
 502
 503        public override void Write(byte[] buffer, int offset, int count)
 47504        {
 47505            ValidateBufferArguments(buffer, offset, count);
 47506            Write(buffer.AsSpan(offset, count));
 47507        }
 508
 509        public override void Write(ReadOnlySpan<byte> buffer)
 47510        {
 47511            ThrowIfNotWritable();
 47512            if (!_headerWritten)
 47513            {
 47514                WriteHeader();
 47515            }
 516
 47517            WriteCore(buffer, GetWriteWorkBuffer());
 47518        }
 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)
 47527        {
 47528            cancellationToken.ThrowIfCancellationRequested();
 47529            ThrowIfNotWritable();
 47530            if (!_headerWritten)
 47531            {
 47532                await WriteHeaderAsync(cancellationToken).ConfigureAwait(false);
 47533            }
 534
 47535            byte[] workBuffer = GetWriteWorkBuffer();
 536
 94537            while (!buffer.IsEmpty)
 47538            {
 47539                int bytesToProcess = Math.Min(buffer.Length, workBuffer.Length);
 540
 47541                buffer[..bytesToProcess].CopyTo(workBuffer);
 47542                ProcessBlock(workBuffer.AsSpan(0, bytesToProcess));
 47543                await _baseStream.WriteAsync(workBuffer.AsMemory(0, bytesToProcess), cancellationToken).ConfigureAwait(f
 544
 47545                buffer = buffer[bytesToProcess..];
 47546            }
 47547        }
 548
 549        public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
 47550        {
 47551            return WriteAsyncCore(buffer, cancellationToken);
 47552        }
 553
 554        protected override void Dispose(bool disposing)
 94555        {
 94556            if (_disposed)
 0557            {
 0558                return;
 559            }
 560
 94561            if (disposing)
 94562            {
 563                try
 94564                {
 94565                    if (_encrypting && !_authCodeFinalized)
 47566                    {
 47567                        FinishEncryptingAsync(isAsync: false, CancellationToken.None).GetAwaiter().GetResult();
 47568                    }
 94569                }
 570                finally
 94571                {
 94572                    _disposed = true;
 94573                    _aes.Dispose();
 94574                    _hmac?.Dispose();
 575
 94576                    if (!_leaveOpen)
 47577                    {
 47578                        _baseStream.Dispose();
 47579                    }
 94580                }
 94581            }
 582
 94583            base.Dispose(disposing);
 94584        }
 585
 586        public override async ValueTask DisposeAsync()
 94587        {
 94588            if (_disposed)
 0589            {
 0590                return;
 591            }
 592
 593            try
 94594            {
 94595                if (_encrypting && !_authCodeFinalized)
 47596                {
 47597                    await FinishEncryptingAsync(isAsync: true, CancellationToken.None).ConfigureAwait(false);
 47598                }
 94599            }
 600            finally
 94601            {
 94602                _aes.Dispose();
 94603                _hmac?.Dispose();
 604
 94605                if (!_leaveOpen)
 47606                {
 47607                    await _baseStream.DisposeAsync().ConfigureAwait(false);
 47608                }
 94609            }
 610
 94611            _disposed = true;
 94612        }
 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)
 94619        {
 94620            Debug.Assert(_encrypting && !_authCodeFinalized);
 621
 622            // Ensure header is written even for empty files
 94623            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
 94636            await WriteAuthCodeCoreAsync(isAsync, cancellationToken).ConfigureAwait(false);
 637
 94638            if (isAsync)
 47639            {
 47640                await _baseStream.FlushAsync(cancellationToken).ConfigureAwait(false);
 47641            }
 642            else
 47643            {
 47644                _baseStream.Flush();
 47645            }
 94646        }
 647
 282648        public override bool CanRead => !_encrypting && !_disposed;
 94649        public override bool CanSeek => false;
 94650        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)