internal static async Task EncryptAsync(CryptoRequest request) { CryptoContainer container = request.ValidateEncryption(); ReportAndCancellationToken token = request.Token ?? new ReportAndCancellationToken(); token.CanReportProgress = request.InData.CanSeek; using (var aes = GetAes()) using (var encryptor = GetEncryptorAndSetAes(aes, request)) { int bufferSize = aes.BlockSize; if (token.CanReportProgress ?? false) { token.NumberOfIterations = (int)Math.Ceiling(request.InData.Length / (double)bufferSize); } CryptoStream cs = new CryptoStream(request.OutData, encryptor, CryptoStreamMode.Write); byte[] buffer = new byte[bufferSize]; int read = 0; int iterationCount = 0; while ((read = await request.InData.ReadAsync(buffer, 0, bufferSize)) > 0) { await cs.WriteAsync(buffer, 0, read); await cs.FlushAsync(); if (token.IsCanceled) { break; } iterationCount++; token.ReportProgressInternal(iterationCount); } if (token.IsCanceled) { return; } cs.FlushFinalBlock(); } if (!request.SkipValidations) { await container.WriteChecksAndEmbeddedDataAsync(); } }
internal static void Decrypt(CryptoRequest request) { CryptoContainer container = request.ValidateDecrypt(request); ReportAndCancellationToken token = request.Token ?? new ReportAndCancellationToken(); token.CanReportProgress = request.InData.CanSeek; using (var aes = GetAes()) using (ICryptoTransform decryptor = GetDecryptorAndSetAes(aes, request)) { int bufferSize = aes.BlockSize; if (token.CanReportProgress ?? false) { token.NumberOfIterations = (int)Math.Ceiling(request.InData.Length / (double)bufferSize); } CryptoStream cs = new CryptoStream(request.OutData, decryptor, CryptoStreamMode.Write); byte[] buffer = new byte[bufferSize]; int read = 0; int iterationCount = 0; while ((read = request.InData.Read(buffer, 0, bufferSize)) > 0) { cs.Write(buffer, 0, read); cs.Flush(); if (token.IsCanceled) { break; } iterationCount++; token.ReportProgressInternal(iterationCount); } if (token.IsCanceled) { return; } cs.FlushFinalBlock(); } }