Beispiel #1
0
    public static void HashEachInput(string[] inputs, bool text, HashFunction hashFunction)
    {
        if (inputs == null)
        {
            DisplayMessage.Error(!text ? "Please specify a file/directory to hash." : "Please specify text to hash.");
            return;
        }
        foreach (string input in inputs)
        {
            try
            {
                switch (text)
                {
                case false when Directory.Exists(input):
                {
                    string[] filePaths  = Directory.GetFiles(input, searchPattern: "*", SearchOption.AllDirectories);
                    int      arrayIndex = Array.IndexOf(inputs, input);
                    if (arrayIndex > 0)
                    {
                        Console.WriteLine();
                    }
                    DisplayMessage.Message(input, "Hashing each file in the directory...");
                    HashEachInput(filePaths, text: false, hashFunction);
                    if (arrayIndex != inputs.Length - 1)
                    {
                        Console.WriteLine();
                    }
                    continue;
                }

                case false when !File.Exists(input):
                    DisplayMessage.NamedError(input, "This file/directory path doesn't exist.");
                    continue;
                }
                using Stream stream = !text ? new FileStream(input, FileMode.Open, FileAccess.Read, FileShare.Read, HashingAlgorithms.BufferSize, FileOptions.SequentialScan) : new MemoryStream(Encoding.UTF8.GetBytes(input));
                byte[] hash = HashingAlgorithms.GetHash(stream, hashFunction);
                DisplayMessage.Message(input, BitConverter.ToString(hash).Replace("-", "").ToLower());
            }
            catch (Exception ex) when(ex is IOException or UnauthorizedAccessException or ArgumentException or SecurityException or NotSupportedException)
            {
                DisplayMessage.NamedError(input, ex.GetType().ToString());
            }
        }
    }