Esempio n. 1
0
        protected override async Task Handle(EncryptFiles request, CancellationToken cancellationToken)
        {
            if (string.IsNullOrWhiteSpace(request.Key))
            {
                throw new ArgumentException("Key must not be empty", nameof(request.Key));
            }

            var fileMap = new List <Tuple <FileInfo, FileInfo> >();

            switch (request.Source)
            {
            case DirectoryInfo sourceDirectory:
                DirectoryInfo targetDirectory;
                switch (request.Target)
                {
                case null:
                    targetDirectory = sourceDirectory;
                    break;

                case DirectoryInfo directoryInfo:
                    targetDirectory = directoryInfo;
                    break;

                default:
                    throw new InvalidOperationException(
                              "Target must be a directory when Source is a directory.");
                }

                if (!targetDirectory.Exists)
                {
                    targetDirectory.Create();
                }

                if (sourceDirectory.Exists)
                {
                    fileMap.AddRange(sourceDirectory.GetFiles()
                                     .Where(info => !info.Extension.Equals(Constants.EncryptedFileExtension,
                                                                           StringComparison.OrdinalIgnoreCase))
                                     .Select(file => new Tuple <FileInfo, FileInfo>(file,
                                                                                    new FileInfo(Path.Combine(targetDirectory.FullName,
                                                                                                              $"{file.Name}{Constants.EncryptedFileExtension}")))));
                }

                break;

            case FileInfo sourceFile:
                FileInfo targetFile;

                switch (request.Target)
                {
                case null:
                    targetFile = new FileInfo($"{sourceFile.FullName}{Constants.EncryptedFileExtension}");
                    break;

                case DirectoryInfo directoryInfo:
                    targetFile = new FileInfo(Path.Combine(directoryInfo.FullName,
                                                           $"{sourceFile.Name}{Constants.EncryptedFileExtension}"));
                    break;

                case FileInfo fileInfo:
                    targetFile = fileInfo;
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(request.Target));
                }

                if (sourceFile.Exists)
                {
                    fileMap.Add(new Tuple <FileInfo, FileInfo>(sourceFile, targetFile));
                }

                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(request.Source));
            }

            var stopwatch = Stopwatch.StartNew();

            foreach (var(source, target) in fileMap)
            {
                var encrypted = await Kryptera.InternalEncryptFileAsync(source, request.Key, cancellationToken);

                if (!encrypted.Success)
                {
                    _logger.LogWarning($"Unable to encrypt {source.FullName.Pastel(Color.DimGray)}.");
                    continue;
                }

                if (!target.Exists || request.ForceOverwrite)
                {
                    if (request.EncryptToBase64)
                    {
                        await File.WriteAllTextAsync(target.FullName, encrypted.EncryptedDataBase64String,
                                                     cancellationToken);
                    }
                    else
                    {
                        await File.WriteAllBytesAsync(target.FullName, encrypted.EncryptedDataBytes, cancellationToken);
                    }

                    var length = request.EncryptToBase64
                        ? encrypted.EncryptedDataBase64String.Length
                        : encrypted.EncryptedDataBytes.Length;

                    _console.Out.WriteLine(
                        $"Wrote {length.ToString().Pastel(Color.DeepSkyBlue)} bytes to {target.FullName.Pastel(Color.DimGray)}.");
                }
                else
                {
                    _logger.LogWarning(
                        $"File {target.FullName.Pastel(Color.DimGray)} already exists. To overwrite, please set the --force option.");
                }
            }

            stopwatch.Stop();
            _logger.LogInformation("Operation completed in {DurationMilliseconds}ms", stopwatch.ElapsedMilliseconds);
        }
 protected override Task Handle(GenerateEncryptionKey request, CancellationToken cancellationToken)
 {
     _console.Out.WriteLine(Kryptera.GenerateKey());
     return(Task.CompletedTask);
 }