Ejemplo n.º 1
0
        public static async Task Main()
        {
            Write("Enter URL:> ");
            var url     = ReadLine();
            var uri     = new Uri(url);
            var request = HttpWebRequestExt.Create(uri)
                          .DoNotTrack()
                          .Accept(Any);

            using var response = await request
                                 .GetAsync()
                                 .ConfigureAwait(false);

            var contentType = Lookup(response.ContentType);

            WriteLine($"Status {response.StatusCode}");
            WriteLine($"Content-Type {contentType.Value}");
            WriteLine($"Content-Length {response.ContentLength}");
            var desktop  = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            var fileName = Path.Combine(desktop, PathExt.FixPath(uri.PathAndQuery.Substring(1)));
            var fileExt  = Path.GetExtension(fileName).Substring(1);

            if (contentType?.PrimaryExtension is object && !contentType.Extensions.Contains(fileExt))
            {
                fileName += "." + contentType.PrimaryExtension;
            }
            var file = new FileInfo(fileName);

            file.Directory.Create();
            using var outStream  = file.Create();
            using var body       = response.GetResponseStream();
            using var progStream = new ProgressStream(body, response.ContentLength, new ConsoleProgress(), false);
            await progStream.CopyToAsync(outStream)
            .ConfigureAwait(false);
        }
Ejemplo n.º 2
0
        /// <summary>Encrypt a file.</summary>
        /// <param name="srcFile">The full path and name of the file to be encrypted.</param>
        /// <param name="destFile">The full path and name of the file to be output.</param>
        /// <param name="password">The password for the encryption.</param>
        public async Task EncryptFileAsync(string srcFile, string destFile, string password)
        {
            var destDir = Path.GetDirectoryName(destFile);

            if (!Directory.Exists(destDir))
            {
                Directory.CreateDirectory(destDir);
            }

            var aes = new AesManaged();

            aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
            aes.KeySize   = aes.LegalKeySizes[0].MaxSize;

            // generate random 16 byte salt value
            var salt = new byte[16];
            var rng  = new RNGCryptoServiceProvider();

            rng.GetBytes(salt);

            // derive key and IV from supplied password
            var key = new Rfc2898DeriveBytes(password, salt, Iterations);

            aes.Key  = key.GetBytes(aes.KeySize / 8);
            aes.IV   = key.GetBytes(aes.BlockSize / 8);
            aes.Mode = CipherMode.CBC;

            // prepend salt value to start of file
            using (var dest = new FileStream(destFile, FileMode.Create, FileAccess.Write, FileShare.Read))
            {
                using (var bw = new BinaryWriter(dest))
                {
                    bw.Write(salt);
                }
            }

            // encrypt the source file to the destination
            var transform = aes.CreateEncryptor(aes.Key, aes.IV);

            using (var destination = new FileStream(destFile, FileMode.Append, FileAccess.Write, FileShare.None))
            {
                using (var cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write))
                {
                    using (var source = new FileStream(srcFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        using (var progress = new ProgressStream(source, srcFile))
                        {
                            progress.ProgressChanged += Progress_ProgressChanged;
                            await progress.CopyToAsync(cryptoStream);
                        }
                    }
                }
            }
        }
Ejemplo n.º 3
0
        /// <summary>Decrypt a file.</summary>
        /// <remarks>
        ///     NB: "Padding is invalid and cannot be removed." is the Universal CryptoServices error.  Make sure the
        ///     password, salt and iterations are correct before getting nervous.
        /// </remarks>
        /// <param name="srcFile">The full path and name of the file to be decrypted.</param>
        /// <param name="destFile">The full path and name of the file to be output.</param>
        /// <param name="password">The password for the decryption.</param>
        public async Task DecryptFileAsync(string srcFile, string destFile, string password)
        {
            var destDir = Path.GetDirectoryName(destFile);

            if (!Directory.Exists(destDir))
            {
                Directory.CreateDirectory(destDir);
            }

            using (var destination = new FileStream(destFile, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                var aes = new AesManaged();
                aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
                aes.KeySize   = aes.LegalKeySizes[0].MaxSize;
                aes.Mode      = CipherMode.CBC;

                using (var source = new FileStream(srcFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    using (var progress = new ProgressStream(source, destFile))
                    {
                        // read the salt from the start of the file
                        byte[] salt;

                        using (var br = new BinaryReader(source, Encoding.Default, true))
                        {
                            salt = br.ReadBytes(16);
                        }

                        // derive key and IV from supplied password
                        var key = new Rfc2898DeriveBytes(password, salt, Iterations);
                        aes.Key  = key.GetBytes(aes.KeySize / 8);
                        aes.IV   = key.GetBytes(aes.BlockSize / 8);
                        aes.Mode = CipherMode.CBC;

                        var transform = aes.CreateDecryptor(aes.Key, aes.IV);

                        using (var cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write))
                        {
                            progress.ProgressChanged += Progress_ProgressChanged;

                            await progress.CopyToAsync(cryptoStream);
                        }
                    }
                }
            }
        }
Ejemplo n.º 4
0
        public override async Task <bool> DownloadUpdate(ReleaseEntry releaseEntry, Action <double>?progress)
        {
            //No need to copy the file if it's what we expect already
            if (releaseEntry.IsValidReleaseEntry(AppMetadata.ApplicationVersion, true))
            {
                Logger.Information("{0} already exists and is what we expect, working with that", releaseEntry.FileLocation);
                return(true);
            }

            var bytesWritten = 0d;

            using var releaseStream = FileHelper.OpenWrite(releaseEntry.FileLocation, releaseEntry.Filesize);
            using var packageStream = new ProgressStream(
                      FileHelper.MakeFileStream(Path.Combine(_folderLocation, releaseEntry.Filename), FileMode.Open, FileAccess.ReadWrite),
                      (count =>
            {
                bytesWritten += count;
                progress?.Invoke(bytesWritten / releaseEntry.Filesize);
            }));

            await packageStream.CopyToAsync(releaseStream);

            return(releaseEntry.CheckReleaseEntry(AppMetadata.ApplicationVersion, true));
        }
Ejemplo n.º 5
0
        protected override void ProcessRecord()
        {
            ProviderInfo destinationProviderInfo;

            var destinationLocation = ResolveDestinationLocation(out destinationProviderInfo);

            var sources = Path.Select(each => {
                ProviderInfo spi;
                var sourceFiles = SessionState.Path.GetResolvedProviderPathFromPSPath(each, out spi);
                return new SourceSet {
                    ProviderInfo = spi,
                    SourcePaths = sourceFiles.ToArray(),
                };
            }).ToArray();

            var providerInfos = sources.Select(each => each.ProviderInfo).Distinct().ToArray();
            if (providerInfos.Length == 1 && providerInfos[0] == destinationProviderInfo) {
                WriteVerbose("Using regular copy-item");
                base.ProcessRecord();
                return;
            }

            bool force = Force;

            var copyOperations = ResolveSourceLocations(sources, destinationLocation).ToArray();

            if (copyOperations.Length > 1 && destinationLocation.IsFile) {
                // source can only be a single file.
                ThrowTerminatingError(new ErrorRecord(new DirectoryNotFoundException(), "0", ErrorCategory.InvalidArgument, null));
                //WriteError(new ErrorRecord(new ClrPlusException("Destination file exists--multiple source files specified."), "ErrorId", ErrorCategory.InvalidArgument, null));
                return;
            }

            var s = new Stopwatch();
            s.Start();
            for  (var i = 0; i < copyOperations.Length;  i++) {
                var operation = copyOperations[i];
                WriteProgress(CreateProgressRecord(1, "Copy", "Copying item {0} of {1}".format(i, copyOperations.Length), 100 * (double)i/copyOperations.Length));

                //Console.WriteLine("COPY '{0}' to '{1}'", operation.Source.AbsolutePath, operation.Destination.AbsolutePath);
                if (!force) {
                    if (operation.Destination.Exists) {
                        ThrowTerminatingError(new ErrorRecord(new ClrPlusException("Destination file '{0}' exists. Must use -force to override".format(operation.Destination.AbsolutePath)), "ErrorId", ErrorCategory.ResourceExists, null));
                        return;
                    }
                }

                using (var inputStream = new ProgressStream(operation.Source.Open(FileMode.Open))) {
                    using (var outputStream = new ProgressStream(operation.Destination.Open(FileMode.Create))) {

                        var inputLength = inputStream.Length;

                        inputStream.BytesRead += (sender, args) => {};
                        CopyOperation operation1 = operation;
                        outputStream.BytesWritten += (sender, args) => WriteProgress(CreateProgressRecord(2, "Copy",
                            "Copying '{0}' to '{1}'".format(operation1.Source.AbsolutePath, operation1.Destination.AbsolutePath), 100*(double)args.StreamPosition/inputLength, 1));

                        Task t = inputStream.CopyToAsync(outputStream, _cancellationToken.Token, false);
                        try {
                            t.RunSynchronously();
                        } catch (TaskCanceledException e) {
                            return;
                        }

                    }
                }

                WriteProgress(CreateCompletedProgressRecord(2, "Copy",
                            "Copying '{0}' to '{1}'".format(operation.Source.AbsolutePath, operation.Destination.AbsolutePath), 1));

               // WriteVerbose("Copy from {0} to {1}".format(operation.Source.AbsolutePath, operation.Destination.AbsolutePath));
            }
            WriteProgress(CreateCompletedProgressRecord(1, "Copy", "Copy finished"));
            s.Stop();
            WriteVerbose("Completed in {0}".format(s.Elapsed));
        }