< Summary

Line coverage
83%
Covered lines: 336
Uncovered lines: 68
Coverable lines: 404
Total lines: 675
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)

https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/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;
 12823        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
 12836        private readonly byte[] _keystreamBuffer = new byte[KeystreamBufferSize];
 12837        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)
 6443        {
 6444            if (OperatingSystem.IsBrowser())
 045            {
 046                throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnPlatform);
 47            }
 48
 6449            return WinZipAesKeyMaterial.GetSaltSize(keySizeBits);
 6450        }
 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)
 19256        {
 19257            if (OperatingSystem.IsBrowser())
 058            {
 059                throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnPlatform);
 60            }
 19261            return WinZipAesKeyMaterial.Create(password, salt, keySizeBits);
 19262        }
 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
 12868        {
 12869            if (OperatingSystem.IsBrowser())
 070            {
 071                throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnPlatform);
 72            }
 73
 12874            ArgumentNullException.ThrowIfNull(baseStream);
 75
 12876            if (!encrypting)
 6477            {
 6478                ReadAndValidateHeaderCore(isAsync: false, baseStream, keyMaterial, CancellationToken.None).GetAwaiter().
 3279            }
 80
 9681            return new WinZipAesStream(baseStream, keyMaterial, totalStreamSize, encrypting, leaveOpen);
 9682        }
 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
 6488        {
 6489            if (OperatingSystem.IsBrowser())
 090            {
 091                throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnPlatform);
 92            }
 93
 6494            ArgumentNullException.ThrowIfNull(baseStream);
 95
 6496            if (!encrypting)
 6497            {
 6498                await ReadAndValidateHeaderCore(isAsync: true, baseStream, keyMaterial, cancellationToken).ConfigureAwai
 3299            }
 100
 32101            return new WinZipAesStream(baseStream, keyMaterial, totalStreamSize, encrypting, leaveOpen);
 32102        }
 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
 128108        {
 128109            if (OperatingSystem.IsBrowser())
 0110            {
 0111                throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnPlatform);
 112            }
 128113            int saltSize = keyMaterial.SaltSize;
 114
 115            // Read salt from stream
 128116            byte[] fileSalt = new byte[saltSize];
 128117            if (isAsync)
 64118            {
 64119                await baseStream.ReadExactlyAsync(fileSalt, cancellationToken).ConfigureAwait(false);
 64120            }
 121            else
 64122            {
 64123                baseStream.ReadExactly(fileSalt);
 64124            }
 125
 126            // Read the 2-byte password verifier from stream
 128127            byte[] verifier = new byte[2];
 128128            if (isAsync)
 64129            {
 64130                await baseStream.ReadExactlyAsync(verifier, cancellationToken).ConfigureAwait(false);
 64131            }
 132            else
 64133            {
 64134                baseStream.ReadExactly(verifier);
 64135            }
 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.
 128139            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.
 128146            if (!CryptographicOperations.FixedTimeEquals(verifier, keyMaterial.PasswordVerifier))
 64147            {
 64148                throw new InvalidDataException(SR.InvalidPassword);
 149            }
 64150        }
 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>
 128156        private WinZipAesStream(Stream baseStream, WinZipAesKeyMaterial keyMaterial, long totalStreamSize, bool encrypti
 128157        {
 128158            if (OperatingSystem.IsBrowser())
 0159            {
 0160                throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnPlatform);
 161            }
 162
 128163            _baseStream = baseStream;
 164
 128165            Debug.Assert((totalStreamSize >= 0) == !encrypting, "Total stream size must be known when decrypting");
 166
 128167            _encrypting = encrypting;
 128168            _totalStreamSize = totalStreamSize;
 128169            _leaveOpen = leaveOpen;
 170
 128171            _aes = Aes.Create();
 172
 128173            _salt = keyMaterial.Salt;
 128174            _passwordVerifier = keyMaterial.PasswordVerifier;
 175
 128176            if (encrypting)
 64177            {
 64178                _encryptedDataSize = -1;
 64179                _encryptedDataRemaining = -1;
 64180            }
 181            else
 64182            {
 64183                int headerSize = checked(keyMaterial.SaltSize + 2); // Salt + Password Verifier
 184                const int hmacSize = 10; // 10-byte HMAC
 185
 64186                _encryptedDataSize = _totalStreamSize - headerSize - hmacSize;
 64187                _encryptedDataRemaining = _encryptedDataSize;
 188
 64189                if (_encryptedDataSize < 0)
 0190                {
 0191                    throw new InvalidDataException(SR.InvalidWinZipSize);
 192                }
 64193            }
 194
 128195            _hmac = IncrementalHash.CreateHMAC(HashAlgorithmName.SHA1, keyMaterial.HmacKey);
 128196            _aes.SetKey(keyMaterial.EncryptionKey);
 128197        }
 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)
 64202        {
 203
 64204            Debug.Assert(_hmac is not null, "HMAC should have been initialized");
 205
 206            // Finalize HMAC computation after reading, so we can use stackalloc
 64207            Span<byte> expectedAuth = stackalloc byte[SHA1.HashSizeInBytes];
 64208            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
 64214            Debug.Assert(storedAuth.Length == 10);
 64215            if (!CryptographicOperations.FixedTimeEquals(storedAuth, expectedAuth.Slice(0, storedAuth.Length)))
 0216            {
 0217                throw new InvalidDataException(SR.WinZipAuthCodeMismatch);
 218            }
 64219        }
 220
 221        private void ValidateAuthCode()
 64222        {
 64223            Debug.Assert(!_encrypting, "ValidateAuthCode should only be called during decryption.");
 224
 64225            if (_authCodeFinalized)
 32226            {
 32227                return;
 228            }
 229
 230            // Read the 10-byte stored authentication code from the stream
 32231            byte[] storedAuth = new byte[10];
 32232            _baseStream.ReadExactly(storedAuth);
 32233            FinalizeAndCompareHMAC(storedAuth);
 32234            _authCodeFinalized = true;
 64235        }
 236
 237        private async Task ValidateAuthCodeAsync(CancellationToken cancellationToken)
 64238        {
 64239            Debug.Assert(!_encrypting, "ValidateAuthCode should only be called during decryption.");
 240
 64241            if (_authCodeFinalized)
 32242            {
 32243                return;
 244            }
 245
 246            // Read the 10-byte stored authentication code from the stream
 32247            byte[] storedAuth = new byte[10];
 32248            await _baseStream.ReadExactlyAsync(storedAuth, cancellationToken).ConfigureAwait(false);
 32249            FinalizeAndCompareHMAC(storedAuth);
 32250            _authCodeFinalized = true;
 64251        }
 252
 253        private async Task WriteHeaderAsync(CancellationToken cancellationToken)
 32254        {
 32255            Debug.Assert(!_headerWritten);
 256
 32257            await _baseStream.WriteAsync(_salt, cancellationToken).ConfigureAwait(false);
 32258            await _baseStream.WriteAsync(_passwordVerifier, cancellationToken).ConfigureAwait(false);
 259
 32260            _headerWritten = true;
 32261        }
 262
 263        private void WriteHeader()
 32264        {
 32265            Debug.Assert(!_headerWritten);
 266
 32267            _baseStream.Write(_salt);
 32268            _baseStream.Write(_passwordVerifier);
 32269            _headerWritten = true;
 32270        }
 271
 272        private void ProcessBlock(Span<byte> buffer)
 128273        {
 128274            Debug.Assert(_hmac is not null, "HMAC should have been initialized");
 275
 256276            while (!buffer.IsEmpty)
 128277            {
 278                // Ensure we have enough keystream bytes available
 128279                int keystreamAvailable = KeystreamBufferSize - _keystreamOffset;
 128280                if (keystreamAvailable == 0)
 128281                {
 128282                    GenerateKeystreamBuffer();
 128283                    keystreamAvailable = KeystreamBufferSize;
 128284                }
 285
 286                // Process as many bytes as possible with the available keystream
 128287                int bytesToProcess = Math.Min(buffer.Length, keystreamAvailable);
 288
 128289                Span<byte> dataSpan = buffer.Slice(0, bytesToProcess);
 128290                ReadOnlySpan<byte> keystreamSpan = _keystreamBuffer.AsSpan(_keystreamOffset, bytesToProcess);
 291
 128292                if (_encrypting)
 64293                {
 294                    // For encryption: XOR first, then HMAC the ciphertext
 64295                    XorBytes(dataSpan, keystreamSpan);
 64296                    _hmac.AppendData(dataSpan);
 64297                }
 298                else
 64299                {
 300                    // For decryption: HMAC first (on ciphertext), then XOR
 64301                    _hmac.AppendData(dataSpan);
 64302                    XorBytes(dataSpan, keystreamSpan);
 64303                }
 304
 128305                _keystreamOffset += bytesToProcess;
 128306                buffer = buffer.Slice(bytesToProcess);
 128307            }
 128308        }
 309
 310        private void GenerateKeystreamBuffer()
 128311        {
 312            // Fill the buffer with all counter values first
 65792313            for (int i = 0; i < KeystreamBufferSize; i += BlockSize)
 32768314            {
 32768315                BinaryPrimitives.WriteUInt128LittleEndian(_keystreamBuffer.AsSpan(i, BlockSize), _counter);
 32768316                _counter++;
 32768317            }
 318
 319            // Encrypt all 256 counter blocks in a single call
 128320            _aes.EncryptEcb(_keystreamBuffer, _keystreamBuffer, PaddingMode.None);
 321
 128322            _keystreamOffset = 0;
 128323        }
 324
 325        private static void XorBytes(Span<byte> dest, ReadOnlySpan<byte> src)
 128326        {
 128327            Debug.Assert(dest.Length <= src.Length);
 328
 7424329            for (int i = 0; i < dest.Length; i++)
 3584330            {
 3584331                dest[i] ^= src[i];
 3584332            }
 128333        }
 334
 335        private async Task WriteAuthCodeCoreAsync(bool isAsync, CancellationToken cancellationToken)
 64336        {
 64337            Debug.Assert(_encrypting, "WriteAuthCode should only be called during encryption.");
 64338            Debug.Assert(_hmac is not null, "HMAC should have been initialized");
 339
 64340            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
 64348            byte[] authCode = new byte[SHA1.HashSizeInBytes];
 349
 64350            if (!_hmac.TryGetHashAndReset(authCode, out int bytesWritten) || bytesWritten < MacSizeInBytes)
 0351            {
 0352                throw new CryptographicException();
 353            }
 64354            if (isAsync)
 32355            {
 356                // WriteAsync requires Memory<byte>, so we must copy to a heap buffer for the async path
 32357                await _baseStream.WriteAsync(authCode.AsMemory(0, MacSizeInBytes), cancellationToken).ConfigureAwait(fal
 32358            }
 359            else
 32360            {
 32361                _baseStream.Write(authCode.AsSpan(0, MacSizeInBytes));
 32362            }
 363
 64364            _authCodeFinalized = true;
 64365        }
 366
 367        private void ThrowIfNotReadable()
 128368        {
 128369            ObjectDisposedException.ThrowIf(_disposed, this);
 370
 128371            if (_encrypting)
 0372            {
 0373                throw new NotSupportedException(SR.ReadingNotSupported);
 374            }
 128375        }
 376
 377        private int GetBytesToRead(int requestedCount)
 128378        {
 128379            if (_encryptedDataRemaining <= 0)
 64380            {
 64381                return 0;
 382            }
 383
 64384            return (int)Math.Min(requestedCount, _encryptedDataRemaining);
 128385        }
 386
 387        public override int Read(byte[] buffer, int offset, int count)
 64388        {
 64389            ValidateBufferArguments(buffer, offset, count);
 64390            return Read(buffer.AsSpan(offset, count));
 64391        }
 392
 393        public override int Read(Span<byte> buffer)
 64394        {
 64395            ThrowIfNotReadable();
 396
 64397            int bytesToRead = GetBytesToRead(buffer.Length);
 64398            if (bytesToRead == 0)
 32399            {
 400                // Only validate auth code when we've actually reached end of encrypted data,
 401                // not when caller simply requested 0 bytes
 32402                if (_encryptedDataRemaining <= 0)
 32403                {
 32404                    ValidateAuthCode();
 32405                }
 32406                return 0;
 407            }
 408
 32409            Span<byte> readBuffer = buffer.Slice(0, bytesToRead);
 32410            int bytesRead = _baseStream.Read(readBuffer);
 411
 32412            if (bytesRead > 0)
 32413            {
 32414                _encryptedDataRemaining -= bytesRead;
 32415                ProcessBlock(readBuffer.Slice(0, bytesRead));
 416
 417                // Validate auth code immediately when we've read all encrypted data
 32418                if (_encryptedDataRemaining <= 0)
 32419                {
 32420                    ValidateAuthCode();
 32421                }
 32422            }
 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
 32429            return bytesRead;
 64430        }
 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
 64439        {
 64440            cancellationToken.ThrowIfCancellationRequested();
 64441            ThrowIfNotReadable();
 442
 64443            int bytesToRead = GetBytesToRead(buffer.Length);
 64444            if (bytesToRead == 0)
 32445            {
 446                // Only validate auth code when we've actually reached end of encrypted data,
 447                // not when caller simply requested 0 bytes
 32448                if (_encryptedDataRemaining <= 0)
 32449                {
 32450                    await ValidateAuthCodeAsync(cancellationToken).ConfigureAwait(false);
 32451                }
 32452                return 0;
 453            }
 454
 32455            int bytesRead = await _baseStream.ReadAsync(buffer.Slice(0, bytesToRead), cancellationToken).ConfigureAwait(
 456
 32457            if (bytesRead > 0)
 32458            {
 32459                _encryptedDataRemaining -= bytesRead;
 32460                ProcessBlock(buffer.Span.Slice(0, bytesRead));
 461
 462                // Validate auth code immediately when we've read all encrypted data
 32463                if (_encryptedDataRemaining <= 0)
 32464                {
 32465                    await ValidateAuthCodeAsync(cancellationToken).ConfigureAwait(false);
 32466                }
 32467            }
 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
 32474            return bytesRead;
 64475        }
 476
 64477        private byte[] GetWriteWorkBuffer() => _writeWorkBuffer ??= new byte[KeystreamBufferSize];
 478
 479        private void WriteCore(ReadOnlySpan<byte> buffer, byte[] workBuffer)
 32480        {
 64481            while (!buffer.IsEmpty)
 32482            {
 32483                int bytesToProcess = Math.Min(buffer.Length, workBuffer.Length);
 484
 32485                buffer[..bytesToProcess].CopyTo(workBuffer);
 32486                ProcessBlock(workBuffer.AsSpan(0, bytesToProcess));
 32487                _baseStream.Write(workBuffer, 0, bytesToProcess);
 488
 32489                buffer = buffer[bytesToProcess..];
 32490            }
 32491        }
 492
 493        private void ThrowIfNotWritable()
 64494        {
 64495            ObjectDisposedException.ThrowIf(_disposed, this);
 496
 64497            if (!_encrypting)
 0498            {
 0499                throw new NotSupportedException(SR.WritingNotSupported);
 500            }
 64501        }
 502
 503        public override void Write(byte[] buffer, int offset, int count)
 32504        {
 32505            ValidateBufferArguments(buffer, offset, count);
 32506            Write(buffer.AsSpan(offset, count));
 32507        }
 508
 509        public override void Write(ReadOnlySpan<byte> buffer)
 32510        {
 32511            ThrowIfNotWritable();
 32512            if (!_headerWritten)
 32513            {
 32514                WriteHeader();
 32515            }
 516
 32517            WriteCore(buffer, GetWriteWorkBuffer());
 32518        }
 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)
 32527        {
 32528            cancellationToken.ThrowIfCancellationRequested();
 32529            ThrowIfNotWritable();
 32530            if (!_headerWritten)
 32531            {
 32532                await WriteHeaderAsync(cancellationToken).ConfigureAwait(false);
 32533            }
 534
 32535            byte[] workBuffer = GetWriteWorkBuffer();
 536
 64537            while (!buffer.IsEmpty)
 32538            {
 32539                int bytesToProcess = Math.Min(buffer.Length, workBuffer.Length);
 540
 32541                buffer[..bytesToProcess].CopyTo(workBuffer);
 32542                ProcessBlock(workBuffer.AsSpan(0, bytesToProcess));
 32543                await _baseStream.WriteAsync(workBuffer.AsMemory(0, bytesToProcess), cancellationToken).ConfigureAwait(f
 544
 32545                buffer = buffer[bytesToProcess..];
 32546            }
 32547        }
 548
 549        public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
 32550        {
 32551            return WriteAsyncCore(buffer, cancellationToken);
 32552        }
 553
 554        protected override void Dispose(bool disposing)
 64555        {
 64556            if (_disposed)
 0557            {
 0558                return;
 559            }
 560
 64561            if (disposing)
 64562            {
 563                try
 64564                {
 64565                    if (_encrypting && !_authCodeFinalized)
 32566                    {
 32567                        FinishEncryptingAsync(isAsync: false, CancellationToken.None).GetAwaiter().GetResult();
 32568                    }
 64569                }
 570                finally
 64571                {
 64572                    _disposed = true;
 64573                    _aes.Dispose();
 64574                    _hmac?.Dispose();
 575
 64576                    if (!_leaveOpen)
 32577                    {
 32578                        _baseStream.Dispose();
 32579                    }
 64580                }
 64581            }
 582
 64583            base.Dispose(disposing);
 64584        }
 585
 586        public override async ValueTask DisposeAsync()
 64587        {
 64588            if (_disposed)
 0589            {
 0590                return;
 591            }
 592
 593            try
 64594            {
 64595                if (_encrypting && !_authCodeFinalized)
 32596                {
 32597                    await FinishEncryptingAsync(isAsync: true, CancellationToken.None).ConfigureAwait(false);
 32598                }
 64599            }
 600            finally
 64601            {
 64602                _aes.Dispose();
 64603                _hmac?.Dispose();
 604
 64605                if (!_leaveOpen)
 32606                {
 32607                    await _baseStream.DisposeAsync().ConfigureAwait(false);
 32608                }
 64609            }
 610
 64611            _disposed = true;
 64612        }
 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)
 64619        {
 64620            Debug.Assert(_encrypting && !_authCodeFinalized);
 621
 622            // Ensure header is written even for empty files
 64623            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
 64636            await WriteAuthCodeCoreAsync(isAsync, cancellationToken).ConfigureAwait(false);
 637
 64638            if (isAsync)
 32639            {
 32640                await _baseStream.FlushAsync(cancellationToken).ConfigureAwait(false);
 32641            }
 642            else
 32643            {
 32644                _baseStream.Flush();
 32645            }
 64646        }
 647
 192648        public override bool CanRead => !_encrypting && !_disposed;
 64649        public override bool CanSeek => false;
 64650        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}
 675

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)