Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Security.Cryptography;
- using System.Threading;
- namespace Hashes
- {
- class CLI
- {
- class HashState
- {
- public float Progress { get; private set; }
- public bool Completed { get; private set; }
- public string Result { get; private set; }
- public HashState(Hasher.Hash hash)
- {
- hash.OnProgressChanged += (object sender, float progress) => Progress = progress;
- hash.OnCompleted += (object sender, byte[] result) =>
- {
- Completed = true;
- Result = BitConverter.ToString(result).Replace("-", "").ToLower();
- };
- }
- }
- Dictionary<string, HashState> hashStates;
- CancellationTokenSource cancellationTokenSource;
- public CLI(Dictionary<string, Hasher.Hash> hashes, CancellationTokenSource cancellationTokenSource)
- {
- this.cancellationTokenSource = cancellationTokenSource;
- hashStates = new Dictionary<string, HashState>();
- foreach (var hash in hashes)
- hashStates[hash.Key] = new HashState(hash.Value);
- Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs e) =>
- {
- if (!cancellationTokenSource.IsCancellationRequested)
- {
- cancellationTokenSource.Cancel(true);
- e.Cancel = true;
- }
- };
- }
- public void PrintProgress()
- {
- while (true)
- {
- Console.Clear();
- foreach (var hashState in hashStates)
- {
- var state = hashState.Value;
- Console.Write("{0}: ", hashState.Key);
- if (state.Completed)
- Console.WriteLine(state.Result);
- else
- Console.WriteLine(state.Progress.ToString("P"));
- }
- if (hashStates.Values.All(s => s.Completed))
- {
- Console.Clear();
- PrintResults();
- break;
- }
- else if (cancellationTokenSource.IsCancellationRequested)
- Console.WriteLine("Aborted");
- else
- Console.WriteLine("Hashing...");
- Thread.Sleep(50);
- }
- }
- public void PrintResults()
- {
- foreach (var hashState in hashStates)
- Console.WriteLine("{0}: {1}", hashState.Key, hashState.Value.Result);
- }
- }
- static class Program
- {
- static void Main(string[] args)
- {
- if (args.Length < 1)
- return;
- var hashes = new Dictionary<string, Hasher.Hash>()
- {
- { "MD5", Hasher.CreateHash(() => MD5.Create()) },
- { "SHA-1", Hasher.CreateHash<SHA1Managed>() },
- { "SHA-256", Hasher.CreateHash<SHA256Managed>() },
- { "SHA-384", Hasher.CreateHash<SHA384Managed>() },
- { "SHA-512", Hasher.CreateHash<SHA512Managed>() }
- };
- var cancellationTokenSource = new CancellationTokenSource();
- var task = Hasher.HashAsync(hashes.Values, args[0], cancellationTokenSource.Token);
- task.Start();
- var cli = new CLI(hashes, cancellationTokenSource);
- if (Console.IsOutputRedirected)
- {
- task.Wait();
- cli.PrintResults();
- }
- else
- {
- cli.PrintProgress();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement