private async Task StoreDataAsync(FileIdentifier id, Stream dataStream, UploadPassword passwordSetting, CancellationToken cancellationToken) { UploadProgress progress = this.GetProgressObject(id); // Copy with progress using (Stream outputStream = this._fileWriter.OpenWriteStream(this._fileStore.GetDataFile(id))) { if (passwordSetting.Enable == true && !String.IsNullOrEmpty(passwordSetting.Password)) { using (Aes crypto = CryptoFactory.CreateCrypto(passwordSetting.Password)) { ICryptoTransform encryptor = crypto.CreateEncryptor(); CryptoMetadata.WriteMetadata(outputStream, crypto); using (CryptoStream cryptoStream = new CryptoStream(outputStream, encryptor, CryptoStreamMode.Write, true)) { await CopyStreamWithProgress(cryptoStream); } } } else { await CopyStreamWithProgress(outputStream); } } async Task CopyStreamWithProgress(Stream outputStream) { using (Stream inputStream = dataStream) { int read; byte[] buffer = new byte[4096]; while ((read = await inputStream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0) { progress.Current += read; await outputStream.WriteAsync(buffer, 0, read, cancellationToken).ConfigureAwait(false); } } } }
public static Stream Create(UploadedFile file, string password) { Stream fileStream = file.GetStream(); Aes? crypto = null; try { crypto = CryptoMetadata.ReadMetadataAndInitializeAlgorithm(fileStream, password); CryptoStream cryptoStream = new CryptoStream( fileStream, crypto.CreateDecryptor(), CryptoStreamMode.Read, false ); return(new CryptoStreamWrapper(crypto, cryptoStream)); } catch (Exception) { fileStream.Dispose(); crypto?.Dispose(); throw; } }