| | | 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 | | |
| | | 4 | | using System.Buffers.Binary; |
| | | 5 | | using System.Diagnostics; |
| | | 6 | | using System.Runtime.Versioning; |
| | | 7 | | using System.Security.Cryptography; |
| | | 8 | | using System.Text; |
| | | 9 | | using System.Threading; |
| | | 10 | | using System.Threading.Tasks; |
| | | 11 | | |
| | | 12 | | namespace 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; |
| | 0 | 23 | | 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 |
| | 0 | 36 | | private readonly byte[] _keystreamBuffer = new byte[KeystreamBufferSize]; |
| | 0 | 37 | | 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) |
| | 0 | 43 | | { |
| | 0 | 44 | | if (OperatingSystem.IsBrowser()) |
| | 0 | 45 | | { |
| | 0 | 46 | | throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnBrowser); |
| | | 47 | | } |
| | | 48 | | |
| | 0 | 49 | | return WinZipAesKeyMaterial.GetSaltSize(keySizeBits); |
| | 0 | 50 | | } |
| | | 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) |
| | 0 | 56 | | { |
| | 0 | 57 | | if (OperatingSystem.IsBrowser()) |
| | 0 | 58 | | { |
| | 0 | 59 | | throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnBrowser); |
| | | 60 | | } |
| | 0 | 61 | | return WinZipAesKeyMaterial.Create(password, salt, keySizeBits); |
| | 0 | 62 | | } |
| | | 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 |
| | 0 | 68 | | { |
| | 0 | 69 | | if (OperatingSystem.IsBrowser()) |
| | 0 | 70 | | { |
| | 0 | 71 | | throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnBrowser); |
| | | 72 | | } |
| | | 73 | | |
| | 0 | 74 | | ArgumentNullException.ThrowIfNull(baseStream); |
| | | 75 | | |
| | 0 | 76 | | if (!encrypting) |
| | 0 | 77 | | { |
| | 0 | 78 | | ReadAndValidateHeaderCore(isAsync: false, baseStream, keyMaterial, CancellationToken.None).GetAwaiter(). |
| | 0 | 79 | | } |
| | | 80 | | |
| | 0 | 81 | | return new WinZipAesStream(baseStream, keyMaterial, totalStreamSize, encrypting, leaveOpen); |
| | 0 | 82 | | } |
| | | 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 |
| | 0 | 88 | | { |
| | 0 | 89 | | if (OperatingSystem.IsBrowser()) |
| | 0 | 90 | | { |
| | 0 | 91 | | throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnBrowser); |
| | | 92 | | } |
| | | 93 | | |
| | 0 | 94 | | ArgumentNullException.ThrowIfNull(baseStream); |
| | | 95 | | |
| | 0 | 96 | | if (!encrypting) |
| | 0 | 97 | | { |
| | 0 | 98 | | await ReadAndValidateHeaderCore(isAsync: true, baseStream, keyMaterial, cancellationToken).ConfigureAwai |
| | 0 | 99 | | } |
| | | 100 | | |
| | 0 | 101 | | return new WinZipAesStream(baseStream, keyMaterial, totalStreamSize, encrypting, leaveOpen); |
| | 0 | 102 | | } |
| | | 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 |
| | 0 | 108 | | { |
| | 0 | 109 | | if (OperatingSystem.IsBrowser()) |
| | 0 | 110 | | { |
| | 0 | 111 | | throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnBrowser); |
| | | 112 | | } |
| | 0 | 113 | | int saltSize = keyMaterial.SaltSize; |
| | | 114 | | |
| | | 115 | | // Read salt from stream |
| | 0 | 116 | | byte[] fileSalt = new byte[saltSize]; |
| | 0 | 117 | | if (isAsync) |
| | 0 | 118 | | { |
| | 0 | 119 | | await baseStream.ReadExactlyAsync(fileSalt, cancellationToken).ConfigureAwait(false); |
| | 0 | 120 | | } |
| | | 121 | | else |
| | 0 | 122 | | { |
| | 0 | 123 | | baseStream.ReadExactly(fileSalt); |
| | 0 | 124 | | } |
| | | 125 | | |
| | | 126 | | // Read the 2-byte password verifier from stream |
| | 0 | 127 | | byte[] verifier = new byte[2]; |
| | 0 | 128 | | if (isAsync) |
| | 0 | 129 | | { |
| | 0 | 130 | | await baseStream.ReadExactlyAsync(verifier, cancellationToken).ConfigureAwait(false); |
| | 0 | 131 | | } |
| | | 132 | | else |
| | 0 | 133 | | { |
| | 0 | 134 | | baseStream.ReadExactly(verifier); |
| | 0 | 135 | | } |
| | | 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. |
| | 0 | 139 | | if (!CryptographicOperations.FixedTimeEquals(fileSalt, keyMaterial.Salt)) |
| | 0 | 140 | | { |
| | 0 | 141 | | 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. |
| | 0 | 146 | | if (!CryptographicOperations.FixedTimeEquals(verifier, keyMaterial.PasswordVerifier)) |
| | 0 | 147 | | { |
| | 0 | 148 | | throw new InvalidDataException(SR.InvalidPassword); |
| | | 149 | | } |
| | 0 | 150 | | } |
| | | 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> |
| | 0 | 156 | | private WinZipAesStream(Stream baseStream, WinZipAesKeyMaterial keyMaterial, long totalStreamSize, bool encrypti |
| | 0 | 157 | | { |
| | 0 | 158 | | if (OperatingSystem.IsBrowser()) |
| | 0 | 159 | | { |
| | 0 | 160 | | throw new PlatformNotSupportedException(SR.WinZipEncryptionNotSupportedOnBrowser); |
| | | 161 | | } |
| | | 162 | | |
| | 0 | 163 | | _baseStream = baseStream; |
| | | 164 | | |
| | 0 | 165 | | Debug.Assert((totalStreamSize >= 0) == !encrypting, "Total stream size must be known when decrypting"); |
| | | 166 | | |
| | 0 | 167 | | _encrypting = encrypting; |
| | 0 | 168 | | _totalStreamSize = totalStreamSize; |
| | 0 | 169 | | _leaveOpen = leaveOpen; |
| | | 170 | | |
| | 0 | 171 | | _aes = Aes.Create(); |
| | | 172 | | |
| | 0 | 173 | | _salt = keyMaterial.Salt; |
| | 0 | 174 | | _passwordVerifier = keyMaterial.PasswordVerifier; |
| | | 175 | | |
| | 0 | 176 | | if (encrypting) |
| | 0 | 177 | | { |
| | 0 | 178 | | _encryptedDataSize = -1; |
| | 0 | 179 | | _encryptedDataRemaining = -1; |
| | 0 | 180 | | } |
| | | 181 | | else |
| | 0 | 182 | | { |
| | 0 | 183 | | int headerSize = checked(keyMaterial.SaltSize + 2); // Salt + Password Verifier |
| | | 184 | | const int hmacSize = 10; // 10-byte HMAC |
| | | 185 | | |
| | 0 | 186 | | _encryptedDataSize = _totalStreamSize - headerSize - hmacSize; |
| | 0 | 187 | | _encryptedDataRemaining = _encryptedDataSize; |
| | | 188 | | |
| | 0 | 189 | | if (_encryptedDataSize < 0) |
| | 0 | 190 | | { |
| | 0 | 191 | | throw new InvalidDataException(SR.InvalidWinZipSize); |
| | | 192 | | } |
| | 0 | 193 | | } |
| | | 194 | | |
| | 0 | 195 | | _hmac = IncrementalHash.CreateHMAC(HashAlgorithmName.SHA1, keyMaterial.HmacKey); |
| | 0 | 196 | | _aes.SetKey(keyMaterial.EncryptionKey); |
| | 0 | 197 | | } |
| | | 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) |
| | 0 | 202 | | { |
| | | 203 | | |
| | 0 | 204 | | Debug.Assert(_hmac is not null, "HMAC should have been initialized"); |
| | | 205 | | |
| | | 206 | | // Finalize HMAC computation after reading, so we can use stackalloc |
| | 0 | 207 | | Span<byte> expectedAuth = stackalloc byte[SHA1.HashSizeInBytes]; |
| | 0 | 208 | | if (!_hmac.TryGetHashAndReset(expectedAuth, out int bytesWritten) || bytesWritten < 10) |
| | 0 | 209 | | { |
| | 0 | 210 | | throw new InvalidDataException(SR.WinZipAuthCodeMismatch); |
| | | 211 | | } |
| | | 212 | | |
| | | 213 | | // Compare the 10 bytes of the expected hash |
| | 0 | 214 | | Debug.Assert(storedAuth.Length == 10); |
| | 0 | 215 | | if (!CryptographicOperations.FixedTimeEquals(storedAuth, expectedAuth.Slice(0, storedAuth.Length))) |
| | 0 | 216 | | { |
| | 0 | 217 | | throw new InvalidDataException(SR.WinZipAuthCodeMismatch); |
| | | 218 | | } |
| | 0 | 219 | | } |
| | | 220 | | |
| | | 221 | | private void ValidateAuthCode() |
| | 0 | 222 | | { |
| | 0 | 223 | | Debug.Assert(!_encrypting, "ValidateAuthCode should only be called during decryption."); |
| | | 224 | | |
| | 0 | 225 | | if (_authCodeFinalized) |
| | 0 | 226 | | { |
| | 0 | 227 | | return; |
| | | 228 | | } |
| | | 229 | | |
| | | 230 | | // Read the 10-byte stored authentication code from the stream |
| | 0 | 231 | | byte[] storedAuth = new byte[10]; |
| | 0 | 232 | | _baseStream.ReadExactly(storedAuth); |
| | 0 | 233 | | FinalizeAndCompareHMAC(storedAuth); |
| | 0 | 234 | | _authCodeFinalized = true; |
| | 0 | 235 | | } |
| | | 236 | | |
| | | 237 | | private async Task ValidateAuthCodeAsync(CancellationToken cancellationToken) |
| | 0 | 238 | | { |
| | 0 | 239 | | Debug.Assert(!_encrypting, "ValidateAuthCode should only be called during decryption."); |
| | | 240 | | |
| | 0 | 241 | | if (_authCodeFinalized) |
| | 0 | 242 | | { |
| | 0 | 243 | | return; |
| | | 244 | | } |
| | | 245 | | |
| | | 246 | | // Read the 10-byte stored authentication code from the stream |
| | 0 | 247 | | byte[] storedAuth = new byte[10]; |
| | 0 | 248 | | await _baseStream.ReadExactlyAsync(storedAuth, cancellationToken).ConfigureAwait(false); |
| | 0 | 249 | | FinalizeAndCompareHMAC(storedAuth); |
| | 0 | 250 | | _authCodeFinalized = true; |
| | 0 | 251 | | } |
| | | 252 | | |
| | | 253 | | private async Task WriteHeaderAsync(CancellationToken cancellationToken) |
| | 0 | 254 | | { |
| | 0 | 255 | | Debug.Assert(!_headerWritten); |
| | | 256 | | |
| | 0 | 257 | | await _baseStream.WriteAsync(_salt, cancellationToken).ConfigureAwait(false); |
| | 0 | 258 | | await _baseStream.WriteAsync(_passwordVerifier, cancellationToken).ConfigureAwait(false); |
| | | 259 | | |
| | 0 | 260 | | _headerWritten = true; |
| | 0 | 261 | | } |
| | | 262 | | |
| | | 263 | | private void WriteHeader() |
| | 0 | 264 | | { |
| | 0 | 265 | | Debug.Assert(!_headerWritten); |
| | | 266 | | |
| | 0 | 267 | | _baseStream.Write(_salt); |
| | 0 | 268 | | _baseStream.Write(_passwordVerifier); |
| | 0 | 269 | | _headerWritten = true; |
| | 0 | 270 | | } |
| | | 271 | | |
| | | 272 | | private void ProcessBlock(Span<byte> buffer) |
| | 0 | 273 | | { |
| | 0 | 274 | | Debug.Assert(_hmac is not null, "HMAC should have been initialized"); |
| | | 275 | | |
| | 0 | 276 | | while (!buffer.IsEmpty) |
| | 0 | 277 | | { |
| | | 278 | | // Ensure we have enough keystream bytes available |
| | 0 | 279 | | int keystreamAvailable = KeystreamBufferSize - _keystreamOffset; |
| | 0 | 280 | | if (keystreamAvailable == 0) |
| | 0 | 281 | | { |
| | 0 | 282 | | GenerateKeystreamBuffer(); |
| | 0 | 283 | | keystreamAvailable = KeystreamBufferSize; |
| | 0 | 284 | | } |
| | | 285 | | |
| | | 286 | | // Process as many bytes as possible with the available keystream |
| | 0 | 287 | | int bytesToProcess = Math.Min(buffer.Length, keystreamAvailable); |
| | | 288 | | |
| | 0 | 289 | | Span<byte> dataSpan = buffer.Slice(0, bytesToProcess); |
| | 0 | 290 | | ReadOnlySpan<byte> keystreamSpan = _keystreamBuffer.AsSpan(_keystreamOffset, bytesToProcess); |
| | | 291 | | |
| | 0 | 292 | | if (_encrypting) |
| | 0 | 293 | | { |
| | | 294 | | // For encryption: XOR first, then HMAC the ciphertext |
| | 0 | 295 | | XorBytes(dataSpan, keystreamSpan); |
| | 0 | 296 | | _hmac.AppendData(dataSpan); |
| | 0 | 297 | | } |
| | | 298 | | else |
| | 0 | 299 | | { |
| | | 300 | | // For decryption: HMAC first (on ciphertext), then XOR |
| | 0 | 301 | | _hmac.AppendData(dataSpan); |
| | 0 | 302 | | XorBytes(dataSpan, keystreamSpan); |
| | 0 | 303 | | } |
| | | 304 | | |
| | 0 | 305 | | _keystreamOffset += bytesToProcess; |
| | 0 | 306 | | buffer = buffer.Slice(bytesToProcess); |
| | 0 | 307 | | } |
| | 0 | 308 | | } |
| | | 309 | | |
| | | 310 | | private void GenerateKeystreamBuffer() |
| | 0 | 311 | | { |
| | | 312 | | // Fill the buffer with all counter values first |
| | 0 | 313 | | for (int i = 0; i < KeystreamBufferSize; i += BlockSize) |
| | 0 | 314 | | { |
| | 0 | 315 | | BinaryPrimitives.WriteUInt128LittleEndian(_keystreamBuffer.AsSpan(i, BlockSize), _counter); |
| | 0 | 316 | | _counter++; |
| | 0 | 317 | | } |
| | | 318 | | |
| | | 319 | | // Encrypt all 256 counter blocks in a single call |
| | 0 | 320 | | _aes.EncryptEcb(_keystreamBuffer, _keystreamBuffer, PaddingMode.None); |
| | | 321 | | |
| | 0 | 322 | | _keystreamOffset = 0; |
| | 0 | 323 | | } |
| | | 324 | | |
| | | 325 | | private static void XorBytes(Span<byte> dest, ReadOnlySpan<byte> src) |
| | 0 | 326 | | { |
| | 0 | 327 | | Debug.Assert(dest.Length <= src.Length); |
| | | 328 | | |
| | 0 | 329 | | for (int i = 0; i < dest.Length; i++) |
| | 0 | 330 | | { |
| | 0 | 331 | | dest[i] ^= src[i]; |
| | 0 | 332 | | } |
| | 0 | 333 | | } |
| | | 334 | | |
| | | 335 | | private async Task WriteAuthCodeCoreAsync(bool isAsync, CancellationToken cancellationToken) |
| | 0 | 336 | | { |
| | 0 | 337 | | Debug.Assert(_encrypting, "WriteAuthCode should only be called during encryption."); |
| | 0 | 338 | | Debug.Assert(_hmac is not null, "HMAC should have been initialized"); |
| | | 339 | | |
| | 0 | 340 | | if (_authCodeFinalized) |
| | 0 | 341 | | { |
| | 0 | 342 | | return; |
| | | 343 | | } |
| | | 344 | | |
| | | 345 | | // WinZip AES spec requires only the first 10 bytes of the HMAC |
| | | 346 | | const int MacSizeInBytes = 10; |
| | | 347 | | |
| | 0 | 348 | | byte[] authCode = new byte[SHA1.HashSizeInBytes]; |
| | | 349 | | |
| | 0 | 350 | | if (!_hmac.TryGetHashAndReset(authCode, out int bytesWritten) || bytesWritten < MacSizeInBytes) |
| | 0 | 351 | | { |
| | 0 | 352 | | throw new CryptographicException(); |
| | | 353 | | } |
| | 0 | 354 | | if (isAsync) |
| | 0 | 355 | | { |
| | | 356 | | // WriteAsync requires Memory<byte>, so we must copy to a heap buffer for the async path |
| | 0 | 357 | | await _baseStream.WriteAsync(authCode.AsMemory(0, MacSizeInBytes), cancellationToken).ConfigureAwait(fal |
| | 0 | 358 | | } |
| | | 359 | | else |
| | 0 | 360 | | { |
| | 0 | 361 | | _baseStream.Write(authCode.AsSpan(0, MacSizeInBytes)); |
| | 0 | 362 | | } |
| | | 363 | | |
| | 0 | 364 | | _authCodeFinalized = true; |
| | 0 | 365 | | } |
| | | 366 | | |
| | | 367 | | private void ThrowIfNotReadable() |
| | 0 | 368 | | { |
| | 0 | 369 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | | 370 | | |
| | 0 | 371 | | if (_encrypting) |
| | 0 | 372 | | { |
| | 0 | 373 | | throw new NotSupportedException(SR.ReadingNotSupported); |
| | | 374 | | } |
| | 0 | 375 | | } |
| | | 376 | | |
| | | 377 | | private int GetBytesToRead(int requestedCount) |
| | 0 | 378 | | { |
| | 0 | 379 | | if (_encryptedDataRemaining <= 0) |
| | 0 | 380 | | { |
| | 0 | 381 | | return 0; |
| | | 382 | | } |
| | | 383 | | |
| | 0 | 384 | | return (int)Math.Min(requestedCount, _encryptedDataRemaining); |
| | 0 | 385 | | } |
| | | 386 | | |
| | | 387 | | public override int Read(byte[] buffer, int offset, int count) |
| | 0 | 388 | | { |
| | 0 | 389 | | ValidateBufferArguments(buffer, offset, count); |
| | 0 | 390 | | return Read(buffer.AsSpan(offset, count)); |
| | 0 | 391 | | } |
| | | 392 | | |
| | | 393 | | public override int Read(Span<byte> buffer) |
| | 0 | 394 | | { |
| | 0 | 395 | | ThrowIfNotReadable(); |
| | | 396 | | |
| | 0 | 397 | | int bytesToRead = GetBytesToRead(buffer.Length); |
| | 0 | 398 | | if (bytesToRead == 0) |
| | 0 | 399 | | { |
| | | 400 | | // Only validate auth code when we've actually reached end of encrypted data, |
| | | 401 | | // not when caller simply requested 0 bytes |
| | 0 | 402 | | if (_encryptedDataRemaining <= 0) |
| | 0 | 403 | | { |
| | 0 | 404 | | ValidateAuthCode(); |
| | 0 | 405 | | } |
| | 0 | 406 | | return 0; |
| | | 407 | | } |
| | | 408 | | |
| | 0 | 409 | | Span<byte> readBuffer = buffer.Slice(0, bytesToRead); |
| | 0 | 410 | | int bytesRead = _baseStream.Read(readBuffer); |
| | | 411 | | |
| | 0 | 412 | | if (bytesRead > 0) |
| | 0 | 413 | | { |
| | 0 | 414 | | _encryptedDataRemaining -= bytesRead; |
| | 0 | 415 | | ProcessBlock(readBuffer.Slice(0, bytesRead)); |
| | | 416 | | |
| | | 417 | | // Validate auth code immediately when we've read all encrypted data |
| | 0 | 418 | | if (_encryptedDataRemaining <= 0) |
| | 0 | 419 | | { |
| | 0 | 420 | | ValidateAuthCode(); |
| | 0 | 421 | | } |
| | 0 | 422 | | } |
| | 0 | 423 | | else if (_encryptedDataRemaining > 0) |
| | 0 | 424 | | { |
| | | 425 | | // Base stream returned 0 bytes but we expected more encrypted data - stream is truncated |
| | 0 | 426 | | throw new InvalidDataException(SR.UnexpectedEndOfStream); |
| | | 427 | | } |
| | | 428 | | |
| | 0 | 429 | | return bytesRead; |
| | 0 | 430 | | } |
| | | 431 | | |
| | | 432 | | public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) |
| | 0 | 433 | | { |
| | 0 | 434 | | ValidateBufferArguments(buffer, offset, count); |
| | 0 | 435 | | return ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); |
| | 0 | 436 | | } |
| | | 437 | | |
| | | 438 | | public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = defaul |
| | 0 | 439 | | { |
| | 0 | 440 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 0 | 441 | | ThrowIfNotReadable(); |
| | | 442 | | |
| | 0 | 443 | | int bytesToRead = GetBytesToRead(buffer.Length); |
| | 0 | 444 | | if (bytesToRead == 0) |
| | 0 | 445 | | { |
| | | 446 | | // Only validate auth code when we've actually reached end of encrypted data, |
| | | 447 | | // not when caller simply requested 0 bytes |
| | 0 | 448 | | if (_encryptedDataRemaining <= 0) |
| | 0 | 449 | | { |
| | 0 | 450 | | await ValidateAuthCodeAsync(cancellationToken).ConfigureAwait(false); |
| | 0 | 451 | | } |
| | 0 | 452 | | return 0; |
| | | 453 | | } |
| | | 454 | | |
| | 0 | 455 | | int bytesRead = await _baseStream.ReadAsync(buffer.Slice(0, bytesToRead), cancellationToken).ConfigureAwait( |
| | | 456 | | |
| | 0 | 457 | | if (bytesRead > 0) |
| | 0 | 458 | | { |
| | 0 | 459 | | _encryptedDataRemaining -= bytesRead; |
| | 0 | 460 | | ProcessBlock(buffer.Span.Slice(0, bytesRead)); |
| | | 461 | | |
| | | 462 | | // Validate auth code immediately when we've read all encrypted data |
| | 0 | 463 | | if (_encryptedDataRemaining <= 0) |
| | 0 | 464 | | { |
| | 0 | 465 | | await ValidateAuthCodeAsync(cancellationToken).ConfigureAwait(false); |
| | 0 | 466 | | } |
| | 0 | 467 | | } |
| | 0 | 468 | | else if (_encryptedDataRemaining > 0) |
| | 0 | 469 | | { |
| | | 470 | | // Base stream returned 0 bytes but we expected more encrypted data - stream is truncated |
| | 0 | 471 | | throw new InvalidDataException(SR.UnexpectedEndOfStream); |
| | | 472 | | } |
| | | 473 | | |
| | 0 | 474 | | return bytesRead; |
| | 0 | 475 | | } |
| | | 476 | | |
| | 0 | 477 | | private byte[] GetWriteWorkBuffer() => _writeWorkBuffer ??= new byte[KeystreamBufferSize]; |
| | | 478 | | |
| | | 479 | | private void WriteCore(ReadOnlySpan<byte> buffer, byte[] workBuffer) |
| | 0 | 480 | | { |
| | 0 | 481 | | while (!buffer.IsEmpty) |
| | 0 | 482 | | { |
| | 0 | 483 | | int bytesToProcess = Math.Min(buffer.Length, workBuffer.Length); |
| | | 484 | | |
| | 0 | 485 | | buffer[..bytesToProcess].CopyTo(workBuffer); |
| | 0 | 486 | | ProcessBlock(workBuffer.AsSpan(0, bytesToProcess)); |
| | 0 | 487 | | _baseStream.Write(workBuffer, 0, bytesToProcess); |
| | | 488 | | |
| | 0 | 489 | | buffer = buffer[bytesToProcess..]; |
| | 0 | 490 | | } |
| | 0 | 491 | | } |
| | | 492 | | |
| | | 493 | | private void ThrowIfNotWritable() |
| | 0 | 494 | | { |
| | 0 | 495 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | | 496 | | |
| | 0 | 497 | | if (!_encrypting) |
| | 0 | 498 | | { |
| | 0 | 499 | | throw new NotSupportedException(SR.WritingNotSupported); |
| | | 500 | | } |
| | 0 | 501 | | } |
| | | 502 | | |
| | | 503 | | public override void Write(byte[] buffer, int offset, int count) |
| | 0 | 504 | | { |
| | 0 | 505 | | ValidateBufferArguments(buffer, offset, count); |
| | 0 | 506 | | Write(buffer.AsSpan(offset, count)); |
| | 0 | 507 | | } |
| | | 508 | | |
| | | 509 | | public override void Write(ReadOnlySpan<byte> buffer) |
| | 0 | 510 | | { |
| | 0 | 511 | | ThrowIfNotWritable(); |
| | 0 | 512 | | if (!_headerWritten) |
| | 0 | 513 | | { |
| | 0 | 514 | | WriteHeader(); |
| | 0 | 515 | | } |
| | | 516 | | |
| | 0 | 517 | | WriteCore(buffer, GetWriteWorkBuffer()); |
| | 0 | 518 | | } |
| | | 519 | | |
| | | 520 | | public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) |
| | 0 | 521 | | { |
| | 0 | 522 | | ValidateBufferArguments(buffer, offset, count); |
| | 0 | 523 | | return WriteAsyncCore(buffer.AsMemory(offset, count), cancellationToken).AsTask(); |
| | 0 | 524 | | } |
| | | 525 | | |
| | | 526 | | private async ValueTask WriteAsyncCore(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken) |
| | 0 | 527 | | { |
| | 0 | 528 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 0 | 529 | | ThrowIfNotWritable(); |
| | 0 | 530 | | if (!_headerWritten) |
| | 0 | 531 | | { |
| | 0 | 532 | | await WriteHeaderAsync(cancellationToken).ConfigureAwait(false); |
| | 0 | 533 | | } |
| | | 534 | | |
| | 0 | 535 | | byte[] workBuffer = GetWriteWorkBuffer(); |
| | | 536 | | |
| | 0 | 537 | | while (!buffer.IsEmpty) |
| | 0 | 538 | | { |
| | 0 | 539 | | int bytesToProcess = Math.Min(buffer.Length, workBuffer.Length); |
| | | 540 | | |
| | 0 | 541 | | buffer[..bytesToProcess].CopyTo(workBuffer); |
| | 0 | 542 | | ProcessBlock(workBuffer.AsSpan(0, bytesToProcess)); |
| | 0 | 543 | | await _baseStream.WriteAsync(workBuffer.AsMemory(0, bytesToProcess), cancellationToken).ConfigureAwait(f |
| | | 544 | | |
| | 0 | 545 | | buffer = buffer[bytesToProcess..]; |
| | 0 | 546 | | } |
| | 0 | 547 | | } |
| | | 548 | | |
| | | 549 | | public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default) |
| | 0 | 550 | | { |
| | 0 | 551 | | return WriteAsyncCore(buffer, cancellationToken); |
| | 0 | 552 | | } |
| | | 553 | | |
| | | 554 | | protected override void Dispose(bool disposing) |
| | 0 | 555 | | { |
| | 0 | 556 | | if (_disposed) |
| | 0 | 557 | | { |
| | 0 | 558 | | return; |
| | | 559 | | } |
| | | 560 | | |
| | 0 | 561 | | if (disposing) |
| | 0 | 562 | | { |
| | | 563 | | try |
| | 0 | 564 | | { |
| | 0 | 565 | | if (_encrypting && !_authCodeFinalized) |
| | 0 | 566 | | { |
| | 0 | 567 | | FinishEncryptingAsync(isAsync: false, CancellationToken.None).GetAwaiter().GetResult(); |
| | 0 | 568 | | } |
| | 0 | 569 | | } |
| | | 570 | | finally |
| | 0 | 571 | | { |
| | 0 | 572 | | _disposed = true; |
| | 0 | 573 | | _aes.Dispose(); |
| | 0 | 574 | | _hmac?.Dispose(); |
| | | 575 | | |
| | 0 | 576 | | if (!_leaveOpen) |
| | 0 | 577 | | { |
| | 0 | 578 | | _baseStream.Dispose(); |
| | 0 | 579 | | } |
| | 0 | 580 | | } |
| | 0 | 581 | | } |
| | | 582 | | |
| | 0 | 583 | | base.Dispose(disposing); |
| | 0 | 584 | | } |
| | | 585 | | |
| | | 586 | | public override async ValueTask DisposeAsync() |
| | 0 | 587 | | { |
| | 0 | 588 | | if (_disposed) |
| | 0 | 589 | | { |
| | 0 | 590 | | return; |
| | | 591 | | } |
| | | 592 | | |
| | | 593 | | try |
| | 0 | 594 | | { |
| | 0 | 595 | | if (_encrypting && !_authCodeFinalized) |
| | 0 | 596 | | { |
| | 0 | 597 | | await FinishEncryptingAsync(isAsync: true, CancellationToken.None).ConfigureAwait(false); |
| | 0 | 598 | | } |
| | 0 | 599 | | } |
| | | 600 | | finally |
| | 0 | 601 | | { |
| | 0 | 602 | | _aes.Dispose(); |
| | 0 | 603 | | _hmac?.Dispose(); |
| | | 604 | | |
| | 0 | 605 | | if (!_leaveOpen) |
| | 0 | 606 | | { |
| | 0 | 607 | | await _baseStream.DisposeAsync().ConfigureAwait(false); |
| | 0 | 608 | | } |
| | 0 | 609 | | } |
| | | 610 | | |
| | 0 | 611 | | _disposed = true; |
| | 0 | 612 | | } |
| | | 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) |
| | 0 | 619 | | { |
| | 0 | 620 | | Debug.Assert(_encrypting && !_authCodeFinalized); |
| | | 621 | | |
| | | 622 | | // Ensure header is written even for empty files |
| | 0 | 623 | | if (!_headerWritten) |
| | 0 | 624 | | { |
| | 0 | 625 | | if (isAsync) |
| | 0 | 626 | | { |
| | 0 | 627 | | await WriteHeaderAsync(cancellationToken).ConfigureAwait(false); |
| | 0 | 628 | | } |
| | | 629 | | else |
| | 0 | 630 | | { |
| | 0 | 631 | | WriteHeader(); |
| | 0 | 632 | | } |
| | 0 | 633 | | } |
| | | 634 | | |
| | | 635 | | // Write Auth Code |
| | 0 | 636 | | await WriteAuthCodeCoreAsync(isAsync, cancellationToken).ConfigureAwait(false); |
| | | 637 | | |
| | 0 | 638 | | if (isAsync) |
| | 0 | 639 | | { |
| | 0 | 640 | | await _baseStream.FlushAsync(cancellationToken).ConfigureAwait(false); |
| | 0 | 641 | | } |
| | | 642 | | else |
| | 0 | 643 | | { |
| | 0 | 644 | | _baseStream.Flush(); |
| | 0 | 645 | | } |
| | 0 | 646 | | } |
| | | 647 | | |
| | 0 | 648 | | public override bool CanRead => !_encrypting && !_disposed; |
| | 0 | 649 | | public override bool CanSeek => false; |
| | 0 | 650 | | public override bool CanWrite => _encrypting && !_disposed; |
| | 0 | 651 | | public override long Length => throw new NotSupportedException(); |
| | | 652 | | |
| | | 653 | | public override long Position |
| | | 654 | | { |
| | 0 | 655 | | get => throw new NotSupportedException(); |
| | 0 | 656 | | set => throw new NotSupportedException(); |
| | | 657 | | } |
| | | 658 | | |
| | | 659 | | public override void Flush() |
| | 0 | 660 | | { |
| | 0 | 661 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | 0 | 662 | | _baseStream.Flush(); |
| | 0 | 663 | | } |
| | | 664 | | |
| | | 665 | | public override async Task FlushAsync(CancellationToken cancellationToken) |
| | 0 | 666 | | { |
| | 0 | 667 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | 0 | 668 | | await _baseStream.FlushAsync(cancellationToken).ConfigureAwait(false); |
| | 0 | 669 | | } |
| | | 670 | | |
| | 0 | 671 | | public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); |
| | 0 | 672 | | public override void SetLength(long value) => throw new NotSupportedException(); |
| | | 673 | | } |
| | | 674 | | } |