< 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
0%
Covered lines: 0
Uncovered lines: 404
Coverable lines: 404
Total lines: 674
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 130
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

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;
 023        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
 036        private readonly byte[] _keystreamBuffer = new byte[KeystreamBufferSize];
 037        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)
 043        {
 044            if (OperatingSystem.IsBrowser())
 045            {
 046                throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnBrowser);
 47            }
 48
 049            return WinZipAesKeyMaterial.GetSaltSize(keySizeBits);
 050        }
 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)
 056        {
 057            if (OperatingSystem.IsBrowser())
 058            {
 059                throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnBrowser);
 60            }
 061            return WinZipAesKeyMaterial.Create(password, salt, keySizeBits);
 062        }
 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
 068        {
 069            if (OperatingSystem.IsBrowser())
 070            {
 071                throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnBrowser);
 72            }
 73
 074            ArgumentNullException.ThrowIfNull(baseStream);
 75
 076            if (!encrypting)
 077            {
 078                ReadAndValidateHeaderCore(isAsync: false, baseStream, keyMaterial, CancellationToken.None).GetAwaiter().
 079            }
 80
 081            return new WinZipAesStream(baseStream, keyMaterial, totalStreamSize, encrypting, leaveOpen);
 082        }
 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
 088        {
 089            if (OperatingSystem.IsBrowser())
 090            {
 091                throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnBrowser);
 92            }
 93
 094            ArgumentNullException.ThrowIfNull(baseStream);
 95
 096            if (!encrypting)
 097            {
 098                await ReadAndValidateHeaderCore(isAsync: true, baseStream, keyMaterial, cancellationToken).ConfigureAwai
 099            }
 100
 0101            return new WinZipAesStream(baseStream, keyMaterial, totalStreamSize, encrypting, leaveOpen);
 0102        }
 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
 0108        {
 0109            if (OperatingSystem.IsBrowser())
 0110            {
 0111                throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnBrowser);
 112            }
 0113            int saltSize = keyMaterial.SaltSize;
 114
 115            // Read salt from stream
 0116            byte[] fileSalt = new byte[saltSize];
 0117            if (isAsync)
 0118            {
 0119                await baseStream.ReadExactlyAsync(fileSalt, cancellationToken).ConfigureAwait(false);
 0120            }
 121            else
 0122            {
 0123                baseStream.ReadExactly(fileSalt);
 0124            }
 125
 126            // Read the 2-byte password verifier from stream
 0127            byte[] verifier = new byte[2];
 0128            if (isAsync)
 0129            {
 0130                await baseStream.ReadExactlyAsync(verifier, cancellationToken).ConfigureAwait(false);
 0131            }
 132            else
 0133            {
 0134                baseStream.ReadExactly(verifier);
 0135            }
 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.
 0139            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.
 0146            if (!CryptographicOperations.FixedTimeEquals(verifier, keyMaterial.PasswordVerifier))
 0147            {
 0148                throw new InvalidDataException(SR.InvalidPassword);
 149            }
 0150        }
 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>
 0156        private WinZipAesStream(Stream baseStream, WinZipAesKeyMaterial keyMaterial, long totalStreamSize, bool encrypti
 0157        {
 0158            if (OperatingSystem.IsBrowser())
 0159            {
 0160                throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnBrowser);
 161            }
 162
 0163            _baseStream = baseStream;
 164
 0165            Debug.Assert((totalStreamSize >= 0) == !encrypting, "Total stream size must be known when decrypting");
 166
 0167            _encrypting = encrypting;
 0168            _totalStreamSize = totalStreamSize;
 0169            _leaveOpen = leaveOpen;
 170
 0171            _aes = Aes.Create();
 172
 0173            _salt = keyMaterial.Salt;
 0174            _passwordVerifier = keyMaterial.PasswordVerifier;
 175
 0176            if (encrypting)
 0177            {
 0178                _encryptedDataSize = -1;
 0179                _encryptedDataRemaining = -1;
 0180            }
 181            else
 0182            {
 0183                int headerSize = checked(keyMaterial.SaltSize + 2); // Salt + Password Verifier
 184                const int hmacSize = 10; // 10-byte HMAC
 185
 0186                _encryptedDataSize = _totalStreamSize - headerSize - hmacSize;
 0187                _encryptedDataRemaining = _encryptedDataSize;
 188
 0189                if (_encryptedDataSize < 0)
 0190                {
 0191                    throw new InvalidDataException(SR.InvalidWinZipSize);
 192                }
 0193            }
 194
 0195            _hmac = IncrementalHash.CreateHMAC(HashAlgorithmName.SHA1, keyMaterial.HmacKey);
 0196            _aes.SetKey(keyMaterial.EncryptionKey);
 0197        }
 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)
 0202        {
 203
 0204            Debug.Assert(_hmac is not null, "HMAC should have been initialized");
 205
 206            // Finalize HMAC computation after reading, so we can use stackalloc
 0207            Span<byte> expectedAuth = stackalloc byte[SHA1.HashSizeInBytes];
 0208            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
 0214            Debug.Assert(storedAuth.Length == 10);
 0215            if (!CryptographicOperations.FixedTimeEquals(storedAuth, expectedAuth.Slice(0, storedAuth.Length)))
 0216            {
 0217                throw new InvalidDataException(SR.WinZipAuthCodeMismatch);
 218            }
 0219        }
 220
 221        private void ValidateAuthCode()
 0222        {
 0223            Debug.Assert(!_encrypting, "ValidateAuthCode should only be called during decryption.");
 224
 0225            if (_authCodeFinalized)
 0226            {
 0227                return;
 228            }
 229
 230            // Read the 10-byte stored authentication code from the stream
 0231            byte[] storedAuth = new byte[10];
 0232            _baseStream.ReadExactly(storedAuth);
 0233            FinalizeAndCompareHMAC(storedAuth);
 0234            _authCodeFinalized = true;
 0235        }
 236
 237        private async Task ValidateAuthCodeAsync(CancellationToken cancellationToken)
 0238        {
 0239            Debug.Assert(!_encrypting, "ValidateAuthCode should only be called during decryption.");
 240
 0241            if (_authCodeFinalized)
 0242            {
 0243                return;
 244            }
 245
 246            // Read the 10-byte stored authentication code from the stream
 0247            byte[] storedAuth = new byte[10];
 0248            await _baseStream.ReadExactlyAsync(storedAuth, cancellationToken).ConfigureAwait(false);
 0249            FinalizeAndCompareHMAC(storedAuth);
 0250            _authCodeFinalized = true;
 0251        }
 252
 253        private async Task WriteHeaderAsync(CancellationToken cancellationToken)
 0254        {
 0255            Debug.Assert(!_headerWritten);
 256
 0257            await _baseStream.WriteAsync(_salt, cancellationToken).ConfigureAwait(false);
 0258            await _baseStream.WriteAsync(_passwordVerifier, cancellationToken).ConfigureAwait(false);
 259
 0260            _headerWritten = true;
 0261        }
 262
 263        private void WriteHeader()
 0264        {
 0265            Debug.Assert(!_headerWritten);
 266
 0267            _baseStream.Write(_salt);
 0268            _baseStream.Write(_passwordVerifier);
 0269            _headerWritten = true;
 0270        }
 271
 272        private void ProcessBlock(Span<byte> buffer)
 0273        {
 0274            Debug.Assert(_hmac is not null, "HMAC should have been initialized");
 275
 0276            while (!buffer.IsEmpty)
 0277            {
 278                // Ensure we have enough keystream bytes available
 0279                int keystreamAvailable = KeystreamBufferSize - _keystreamOffset;
 0280                if (keystreamAvailable == 0)
 0281                {
 0282                    GenerateKeystreamBuffer();
 0283                    keystreamAvailable = KeystreamBufferSize;
 0284                }
 285
 286                // Process as many bytes as possible with the available keystream
 0287                int bytesToProcess = Math.Min(buffer.Length, keystreamAvailable);
 288
 0289                Span<byte> dataSpan = buffer.Slice(0, bytesToProcess);
 0290                ReadOnlySpan<byte> keystreamSpan = _keystreamBuffer.AsSpan(_keystreamOffset, bytesToProcess);
 291
 0292                if (_encrypting)
 0293                {
 294                    // For encryption: XOR first, then HMAC the ciphertext
 0295                    XorBytes(dataSpan, keystreamSpan);
 0296                    _hmac.AppendData(dataSpan);
 0297                }
 298                else
 0299                {
 300                    // For decryption: HMAC first (on ciphertext), then XOR
 0301                    _hmac.AppendData(dataSpan);
 0302                    XorBytes(dataSpan, keystreamSpan);
 0303                }
 304
 0305                _keystreamOffset += bytesToProcess;
 0306                buffer = buffer.Slice(bytesToProcess);
 0307            }
 0308        }
 309
 310        private void GenerateKeystreamBuffer()
 0311        {
 312            // Fill the buffer with all counter values first
 0313            for (int i = 0; i < KeystreamBufferSize; i += BlockSize)
 0314            {
 0315                BinaryPrimitives.WriteUInt128LittleEndian(_keystreamBuffer.AsSpan(i, BlockSize), _counter);
 0316                _counter++;
 0317            }
 318
 319            // Encrypt all 256 counter blocks in a single call
 0320            _aes.EncryptEcb(_keystreamBuffer, _keystreamBuffer, PaddingMode.None);
 321
 0322            _keystreamOffset = 0;
 0323        }
 324
 325        private static void XorBytes(Span<byte> dest, ReadOnlySpan<byte> src)
 0326        {
 0327            Debug.Assert(dest.Length <= src.Length);
 328
 0329            for (int i = 0; i < dest.Length; i++)
 0330            {
 0331                dest[i] ^= src[i];
 0332            }
 0333        }
 334
 335        private async Task WriteAuthCodeCoreAsync(bool isAsync, CancellationToken cancellationToken)
 0336        {
 0337            Debug.Assert(_encrypting, "WriteAuthCode should only be called during encryption.");
 0338            Debug.Assert(_hmac is not null, "HMAC should have been initialized");
 339
 0340            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
 0348            byte[] authCode = new byte[SHA1.HashSizeInBytes];
 349
 0350            if (!_hmac.TryGetHashAndReset(authCode, out int bytesWritten) || bytesWritten < MacSizeInBytes)
 0351            {
 0352                throw new CryptographicException();
 353            }
 0354            if (isAsync)
 0355            {
 356                // WriteAsync requires Memory<byte>, so we must copy to a heap buffer for the async path
 0357                await _baseStream.WriteAsync(authCode.AsMemory(0, MacSizeInBytes), cancellationToken).ConfigureAwait(fal
 0358            }
 359            else
 0360            {
 0361                _baseStream.Write(authCode.AsSpan(0, MacSizeInBytes));
 0362            }
 363
 0364            _authCodeFinalized = true;
 0365        }
 366
 367        private void ThrowIfNotReadable()
 0368        {
 0369            ObjectDisposedException.ThrowIf(_disposed, this);
 370
 0371            if (_encrypting)
 0372            {
 0373                throw new NotSupportedException(SR.ReadingNotSupported);
 374            }
 0375        }
 376
 377        private int GetBytesToRead(int requestedCount)
 0378        {
 0379            if (_encryptedDataRemaining <= 0)
 0380            {
 0381                return 0;
 382            }
 383
 0384            return (int)Math.Min(requestedCount, _encryptedDataRemaining);
 0385        }
 386
 387        public override int Read(byte[] buffer, int offset, int count)
 0388        {
 0389            ValidateBufferArguments(buffer, offset, count);
 0390            return Read(buffer.AsSpan(offset, count));
 0391        }
 392
 393        public override int Read(Span<byte> buffer)
 0394        {
 0395            ThrowIfNotReadable();
 396
 0397            int bytesToRead = GetBytesToRead(buffer.Length);
 0398            if (bytesToRead == 0)
 0399            {
 400                // Only validate auth code when we've actually reached end of encrypted data,
 401                // not when caller simply requested 0 bytes
 0402                if (_encryptedDataRemaining <= 0)
 0403                {
 0404                    ValidateAuthCode();
 0405                }
 0406                return 0;
 407            }
 408
 0409            Span<byte> readBuffer = buffer.Slice(0, bytesToRead);
 0410            int bytesRead = _baseStream.Read(readBuffer);
 411
 0412            if (bytesRead > 0)
 0413            {
 0414                _encryptedDataRemaining -= bytesRead;
 0415                ProcessBlock(readBuffer.Slice(0, bytesRead));
 416
 417                // Validate auth code immediately when we've read all encrypted data
 0418                if (_encryptedDataRemaining <= 0)
 0419                {
 0420                    ValidateAuthCode();
 0421                }
 0422            }
 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
 0429            return bytesRead;
 0430        }
 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
 0439        {
 0440            cancellationToken.ThrowIfCancellationRequested();
 0441            ThrowIfNotReadable();
 442
 0443            int bytesToRead = GetBytesToRead(buffer.Length);
 0444            if (bytesToRead == 0)
 0445            {
 446                // Only validate auth code when we've actually reached end of encrypted data,
 447                // not when caller simply requested 0 bytes
 0448                if (_encryptedDataRemaining <= 0)
 0449                {
 0450                    await ValidateAuthCodeAsync(cancellationToken).ConfigureAwait(false);
 0451                }
 0452                return 0;
 453            }
 454
 0455            int bytesRead = await _baseStream.ReadAsync(buffer.Slice(0, bytesToRead), cancellationToken).ConfigureAwait(
 456
 0457            if (bytesRead > 0)
 0458            {
 0459                _encryptedDataRemaining -= bytesRead;
 0460                ProcessBlock(buffer.Span.Slice(0, bytesRead));
 461
 462                // Validate auth code immediately when we've read all encrypted data
 0463                if (_encryptedDataRemaining <= 0)
 0464                {
 0465                    await ValidateAuthCodeAsync(cancellationToken).ConfigureAwait(false);
 0466                }
 0467            }
 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
 0474            return bytesRead;
 0475        }
 476
 0477        private byte[] GetWriteWorkBuffer() => _writeWorkBuffer ??= new byte[KeystreamBufferSize];
 478
 479        private void WriteCore(ReadOnlySpan<byte> buffer, byte[] workBuffer)
 0480        {
 0481            while (!buffer.IsEmpty)
 0482            {
 0483                int bytesToProcess = Math.Min(buffer.Length, workBuffer.Length);
 484
 0485                buffer[..bytesToProcess].CopyTo(workBuffer);
 0486                ProcessBlock(workBuffer.AsSpan(0, bytesToProcess));
 0487                _baseStream.Write(workBuffer, 0, bytesToProcess);
 488
 0489                buffer = buffer[bytesToProcess..];
 0490            }
 0491        }
 492
 493        private void ThrowIfNotWritable()
 0494        {
 0495            ObjectDisposedException.ThrowIf(_disposed, this);
 496
 0497            if (!_encrypting)
 0498            {
 0499                throw new NotSupportedException(SR.WritingNotSupported);
 500            }
 0501        }
 502
 503        public override void Write(byte[] buffer, int offset, int count)
 0504        {
 0505            ValidateBufferArguments(buffer, offset, count);
 0506            Write(buffer.AsSpan(offset, count));
 0507        }
 508
 509        public override void Write(ReadOnlySpan<byte> buffer)
 0510        {
 0511            ThrowIfNotWritable();
 0512            if (!_headerWritten)
 0513            {
 0514                WriteHeader();
 0515            }
 516
 0517            WriteCore(buffer, GetWriteWorkBuffer());
 0518        }
 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)
 0527        {
 0528            cancellationToken.ThrowIfCancellationRequested();
 0529            ThrowIfNotWritable();
 0530            if (!_headerWritten)
 0531            {
 0532                await WriteHeaderAsync(cancellationToken).ConfigureAwait(false);
 0533            }
 534
 0535            byte[] workBuffer = GetWriteWorkBuffer();
 536
 0537            while (!buffer.IsEmpty)
 0538            {
 0539                int bytesToProcess = Math.Min(buffer.Length, workBuffer.Length);
 540
 0541                buffer[..bytesToProcess].CopyTo(workBuffer);
 0542                ProcessBlock(workBuffer.AsSpan(0, bytesToProcess));
 0543                await _baseStream.WriteAsync(workBuffer.AsMemory(0, bytesToProcess), cancellationToken).ConfigureAwait(f
 544
 0545                buffer = buffer[bytesToProcess..];
 0546            }
 0547        }
 548
 549        public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
 0550        {
 0551            return WriteAsyncCore(buffer, cancellationToken);
 0552        }
 553
 554        protected override void Dispose(bool disposing)
 0555        {
 0556            if (_disposed)
 0557            {
 0558                return;
 559            }
 560
 0561            if (disposing)
 0562            {
 563                try
 0564                {
 0565                    if (_encrypting && !_authCodeFinalized)
 0566                    {
 0567                        FinishEncryptingAsync(isAsync: false, CancellationToken.None).GetAwaiter().GetResult();
 0568                    }
 0569                }
 570                finally
 0571                {
 0572                    _disposed = true;
 0573                    _aes.Dispose();
 0574                    _hmac?.Dispose();
 575
 0576                    if (!_leaveOpen)
 0577                    {
 0578                        _baseStream.Dispose();
 0579                    }
 0580                }
 0581            }
 582
 0583            base.Dispose(disposing);
 0584        }
 585
 586        public override async ValueTask DisposeAsync()
 0587        {
 0588            if (_disposed)
 0589            {
 0590                return;
 591            }
 592
 593            try
 0594            {
 0595                if (_encrypting && !_authCodeFinalized)
 0596                {
 0597                    await FinishEncryptingAsync(isAsync: true, CancellationToken.None).ConfigureAwait(false);
 0598                }
 0599            }
 600            finally
 0601            {
 0602                _aes.Dispose();
 0603                _hmac?.Dispose();
 604
 0605                if (!_leaveOpen)
 0606                {
 0607                    await _baseStream.DisposeAsync().ConfigureAwait(false);
 0608                }
 0609            }
 610
 0611            _disposed = true;
 0612        }
 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)
 0619        {
 0620            Debug.Assert(_encrypting && !_authCodeFinalized);
 621
 622            // Ensure header is written even for empty files
 0623            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
 0636            await WriteAuthCodeCoreAsync(isAsync, cancellationToken).ConfigureAwait(false);
 637
 0638            if (isAsync)
 0639            {
 0640                await _baseStream.FlushAsync(cancellationToken).ConfigureAwait(false);
 0641            }
 642            else
 0643            {
 0644                _baseStream.Flush();
 0645            }
 0646        }
 647
 0648        public override bool CanRead => !_encrypting && !_disposed;
 0649        public override bool CanSeek => false;
 0650        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)