示例#1
0
        public void PostJoin()
        {
            var fhc = new FileHashCalculator();

            fhc.CalculateHashes(GameModes);
            SendMessageToHost(FILE_HASH_COMMAND + " " + fhc.GetCompleteHash());
        }
        public void TestCalculateBinaryFile()
        {
            var calculator     = new FileHashCalculator();
            var filePathInput  = "tux.png";
            var hashTypeInputs = new[]
            {
                HashType.MD5,
                HashType.SHA1,
                HashType.SHA256,
                HashType.SHA512,
            };
            var expectedHasheStrings = new[]
            {
                "bede490bfe83a2847e1503b3eb5085c7",
                "be598b6d3e3f4f4232abbdc1e90ff900a0c3ccd2",
                "8fc6897c39e60c0d246d992c9b7057ac483f37a7b0d85b69bdc42c652e9a60ee",
                "7b9f4e15ee56cdcf075a736ffb2766e44573601fbbdc485a9bf4a710ee49b41d5c57367ebbf9caecf995404e2f14e98a61986488a0981433ea228d60c86a5a09",
            };

            for (var i = 0; i < hashTypeInputs.Length; i++)
            {
                var hashTypeInput      = hashTypeInputs[i];
                var actualHash         = calculator.Calculate(filePathInput, hashTypeInput);
                var expectedHashString = expectedHasheStrings[i];
                Assert.Equal(expectedHashString, actualHash.ComputedHash.ToHashString());
            }
        }
        public void TestCalculateAsciiFile()
        {
            var calculator     = new FileHashCalculator();
            var filePathInput  = "tux.txt";
            var hashTypeInputs = new[]
            {
                HashType.MD5,
                HashType.SHA1,
                HashType.SHA256,
                HashType.SHA512,
            };
            var expectedHasheStrings = new[]
            {
                "5ab6e4b98bc7fb716fc07ed98fedf802",
                "2970eb1fef549b6a4039e7fd2336ba16b18bcbd2",
                "ec2dc675422c8eeb1eef26e7c67c3d74713e947bda7378896d8e3cf4dc5f0161",
                "b6e7a9b249cdfecdd037c1615dbfdfa35cd0e54e08cd27ed88fceb97296dfa1c512ecf636364f0c9ed6a49cee3574ea91327efc5969bd918175441777e8bc07f",
            };

            for (var i = 0; i < hashTypeInputs.Length; i++)
            {
                var hashTypeInput      = hashTypeInputs[i];
                var actualHash         = calculator.Calculate(filePathInput, hashTypeInput);
                var expectedHashString = expectedHasheStrings[i];
                Assert.Equal(expectedHashString, actualHash.ComputedHash.ToHashString());
            }
        }
示例#4
0
        private string Act(string filePath)
        {
            var calculator = new FileHashCalculator();
            var fileHash   = calculator.Get(filePath);

            return(fileHash);
        }
        static void Main()
        {
            var commandArgumentsParser = new CommandArgumentsParser();
            var fileHashCalculator     = new FileHashCalculator();
            var gitHubHttpClient       = new HttpClient();

            gitHubHttpClient.BaseAddress = new Uri(GitHubRepositoriesApiConstants.BaseUri);
            gitHubHttpClient.DefaultRequestHeaders.UserAgent.ParseAdd($"{Application.ProductName} {Application.ProductVersion}");
            var releaseProvider = new GitHubRepositoryReleaseProvider(
                gitHubHttpClient,
                new GitHubRepositoryReleaseProviderSetting
            {
                OwnerName      = "yossiejs",
                RepositoryName = "AppSight.FileHashChecker",
            });
            var updateManager = new UpdateManager(
                releaseProvider,
                Application.ProductVersion);

            Application.SetHighDpiMode(HighDpiMode.SystemAware);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1(
                                commandArgumentsParser,
                                fileHashCalculator,
                                updateManager));
        }
示例#6
0
        public void PostJoin()
        {
            var fhc = new FileHashCalculator();

            fhc.CalculateHashes(gameModes);
            SendMessageToHost(FILE_HASH_COMMAND + " " + fhc.GetCompleteHash());
            UpdateDiscordPresence(true);
        }
示例#7
0
            public void Should_Throw_If_File_Path_Is_Null()
            {
                // Given
                var fileSystem = Substitute.For <IFileSystem>();
                var calculator = new FileHashCalculator(fileSystem);

                // When
                var result = Record.Exception(() => calculator.Calculate(null, HashAlgorithm.MD5));

                // Then
                Assert.IsArgumentNullException(result, "filePath");
            }
示例#8
0
        public Form1(
            CommandArgumentsParser commandArgumentsParser,
            FileHashCalculator fileHashCaluculator,
            IUpdateManager updateManager)
        {
            _commandArgumentsParser = commandArgumentsParser ?? throw new ArgumentNullException(nameof(commandArgumentsParser));
            _fileHashCalculator     = fileHashCaluculator ?? throw new ArgumentNullException(nameof(fileHashCaluculator));
            _updateManager          = updateManager ?? throw new ArgumentNullException(nameof(updateManager));
            // for debugging localization
            // Thread.CurrentThread.CurrentUICulture = new CultureInfo("ja-JP");
            InitializeComponent();

            _updateManager.UpdateFound += new EventHandler <UpdateFoundEventArgs>(HandleUpdateFound);
            _resourceManager            = new ResourceManager(typeof(Form1));
        }
示例#9
0
            public void Should_Throw_If_File_Does_Not_Exist()
            {
                // Given
                var fileSystem = Substitute.For <IFileSystem>();
                var file       = Substitute.For <IFile>();

                file.Exists.Returns(false);
                fileSystem.GetFile(Arg.Any <FilePath>()).Returns(file);

                var calculator = new FileHashCalculator(fileSystem);

                // When
                var result = Record.Exception(() => calculator.Calculate("./non-existent-path", HashAlgorithm.MD5));

                // Then
                Assert.IsExceptionWithMessage <CakeException>(result, "File 'non-existent-path' does not exist.");
            }
        /// <summary>
        /// Called when the local user has joined the game channel.
        /// </summary>
        public void OnJoined()
        {
            FileHashCalculator fhc = new FileHashCalculator();

            fhc.CalculateHashes(gameModes);

            if (IsHost)
            {
                connectionManager.SendCustomMessage(new QueuedMessage(
                                                        string.Format("MODE {0} +klnNs {1} {2}", channel.ChannelName,
                                                                      channel.Password, SGPlayers.Count),
                                                        QueuedMessageType.SYSTEM_MESSAGE, 50));

                connectionManager.SendCustomMessage(new QueuedMessage(
                                                        string.Format("TOPIC {0} :{1}", channel.ChannelName,
                                                                      ProgramConstants.CNCNET_PROTOCOL_REVISION + ";" + localGame.ToLower()),
                                                        QueuedMessageType.SYSTEM_MESSAGE, 50));

                gameFilesHash = fhc.GetCompleteHash();

                gameBroadcastTimer.Enabled = true;
                gameBroadcastTimer.Start();
                gameBroadcastTimer.SetTime(TimeSpan.FromSeconds(INITIAL_GAME_BROADCAST_DELAY));
            }
            else
            {
                channel.SendCTCPMessage(FILE_HASH_CTCP_COMMAND + " " + fhc.GetCompleteHash(), QueuedMessageType.SYSTEM_MESSAGE, 10);

                channel.SendCTCPMessage(TUNNEL_PING_CTCP_COMMAND + " " + tunnel.PingInMs, QueuedMessageType.SYSTEM_MESSAGE, 10);

                if (tunnel.PingInMs < 0)
                {
                    AddNotice(ProgramConstants.PLAYERNAME + " - unknown ping to tunnel server.");
                }
                else
                {
                    AddNotice(ProgramConstants.PLAYERNAME + " - ping to tunnel server: " + tunnel.PingInMs + " ms");
                }
            }

            topBar.AddPrimarySwitchable(this);
            topBar.SwitchToPrimary();
            WindowManager.SelectedControl = tbChatInput;
            UpdateDiscordPresence(true);
        }
示例#11
0
        public void SetUp(bool isHost,
                          IPEndPoint hostEndPoint, TcpClient client,
                          int loadedGameId)
        {
            Refresh(isHost);

            this.hostEndPoint = hostEndPoint;

            this.loadedGameId = loadedGameId;

            started = false;

            if (isHost)
            {
                Thread thread = new Thread(ListenForClients);
                thread.Start();

                this.client = new TcpClient();
                this.client.Connect("127.0.0.1", ProgramConstants.LAN_GAME_LOBBY_PORT);

                byte[] buffer = encoding.GetBytes(PLAYER_JOIN_COMMAND +
                                                  ProgramConstants.LAN_DATA_SEPARATOR + ProgramConstants.PLAYERNAME +
                                                  ProgramConstants.LAN_DATA_SEPARATOR + loadedGameId);

                this.client.GetStream().Write(buffer, 0, buffer.Length);
                this.client.GetStream().Flush();

                var fhc = new FileHashCalculator();
                fhc.CalculateHashes(gameModes);
                localFileHash = fhc.GetCompleteHash();
            }
            else
            {
                this.client = client;
            }

            new Thread(HandleServerCommunication).Start();

            if (IsHost)
            {
                CopyPlayerDataToUI();
            }

            WindowManager.SelectedControl = tbChatInput;
        }
示例#12
0
        public IEnumerable<EntryCheckResult> ValidateEntries(IEnumerable<ChecksumFileEntry> checksumFileEntries, string defaultHashAlgorithm)
        {
            try
            {
                this.state = StateType.InProgress;
                var entries = checksumFileEntries.ToArray();
                this.entriesCount = entries.Length;
                this.entriesProcessed = 0;

                var results = new List<EntryCheckResult>();
                foreach (var entry in entries)
                {
                    if (this.shouldStop)
                    {
                        break;
                    }

                    this.StartProcessingEntry(entry);
                    this.entryCalculator = new FileHashCalculator();

                    if (entry.HashType != null)
                    {
                        this.entryCalculator.HashAlgorithm = CryptoUtils.ToHashAlgorithm(entry.HashType);
                    }
                    else if (entry.HashType == null && this.DefaultHashType != null)
                    {
                        this.entryCalculator.HashAlgorithm = CryptoUtils.ToHashAlgorithm(this.DefaultHashType.Value);
                    }
                    else
                    {
                        throw new InvalidOperationException("Property 'DefaultHashType' must be set if individual entry hash type is undefined");
                    }

                    this.entryCalculator.ChunkProcessed += this.OnEntryChunkProcessed;

                    string fullEntryPath;
                    if (Path.IsPathRooted(entry.Path))
                    {
                        fullEntryPath = entry.Path;
                    }
                    else
                    {
                        if (!Directory.Exists(this.BaseDir))
                        {
                            throw new InvalidOperationException("Property BaseDir is required, but directory not found");
                        }

                        fullEntryPath = Path.Combine(this.BaseDir, entry.Path);
                    }

                    EntryResultType entryResultType;
                    if (!File.Exists(fullEntryPath))
                    {
                        entryResultType = EntryResultType.NotFound;
                        this.notFoundCount++;
                    }
                    else
                    {
                        var calculatedHash = this.entryCalculator.CalculateFileHash(fullEntryPath);

                        if (this.entryCalculator.HashCalculated)
                        {
                            bool valid = ConvertUtils.ByteArraysEqual(calculatedHash, ConvertUtils.ToBytes(entry.Hash));
                            entryResultType = valid ? EntryResultType.Correct : EntryResultType.Wrong;
                            if (valid)
                            {
                                this.validCount++;
                            }
                            else
                            {
                                this.wrongCount++;
                            }
                        }
                        else
                        {
                            entryResultType = EntryResultType.Aborted;
                        }
                    }

                    var entryResult = new EntryCheckResult(entry.Hash, entry.Path, entry.HashType, entryResultType);
                    results.Add(entryResult);

                    this.entriesProcessed++;
                    this.OnEntryProcessed(entryResult);

                    // Free
                    this.entryCalculator.ChunkProcessed -= this.OnEntryChunkProcessed;
                    this.entryCalculator = null;
                }

                return results;
            }
            finally
            {
                this.state = StateType.Finished;
                this.OnFinished();
            }
        }
        private void ValidateFile()
        {
            try
            {
                if (!Clipboard.ContainsText())
                {
                    CustomMessageBoxes.Warning("No hash in Clipboard to compare");
                    Application.Exit();
                }

                string expectedHash = Clipboard.GetText();

                HashType hashType;
                try
                {
                    hashType = CryptoUtils.DetectHashType(expectedHash.Length);
                }
                catch (ArgumentException ex)
                {
                    throw new InvalidHashException("That's not a valid hash in clipboard", ex);
                }

                this.tbHashInClipboard.Text = string.Format("{0} ({1})", expectedHash.ToUpperInvariant(), hashType);
                this.fileHashCalculator = new FileHashCalculator { HashAlgorithm = CryptoUtils.ToHashAlgorithm(hashType) };
                this.fileHashCalculator.ChunkProcessed += (processed, total) => this.SetProgressThreadSafe((int)((processed * 100) / total));

                this.fileHashCalculator.Calculated += (actualHash) =>
                {
                    var actualHashString = ConvertUtils.ToString(actualHash);
                    this.tbActualHash.Invoke(new Action(() => { this.tbActualHash.Text = actualHashString; }));
                    bool isValid = ConvertUtils.ByteArraysEqual(actualHash, ConvertUtils.ToBytes(expectedHash));
                    this.SetResultTextThreadSafe(isValid ? "Correct" : "Wrong", isValid);
                };

                this.fileHashCalculator.Finished += () =>
                    {
                        if (!this.fileHashCalculator.HashCalculated)
                        {
                            this.SetResultTextThreadSafe("Stopped", false);
                        }
                    };

                this.validatingThread = new Thread(this.CalculateHashAsync);
                this.validatingThread.Start(new ValidateHashParams
                {
                    FilePath = this.fileToValidate,
                    ExpectedHash = expectedHash,
                    FileHashCalculator = this.fileHashCalculator
                });
            }
            catch (InvalidHashException ex)
            {
                CustomMessageBoxes.Error(ex.Message);
                Application.Exit();
            }
            catch (Exception ex)
            {
                CustomMessageBoxes.Error("Error while comparing to hash in clipboard: " + ex.Message);
                Application.Exit();
            }
        }