示例#1
0
        // hashing overloads for different inputs
        // string input, byte input, with and without password
        // needs to return byte or string depending on input
        // if string input => string output
        // if byte input => byte output
        public string Hash(HashType type, string input)
        {
            switch (type)
            {
            case HashType.Md5Hash:
                Md5Hash md5 = new Md5Hash();
                return(md5.Hash(input));

            case HashType.Sha1Hash:
                Sha1Hash sha1 = new Sha1Hash();
                return(sha1.Hash(input));

            case HashType.Sha2Hash:
                Sha2Hash sha2 = new Sha2Hash();
                return(sha2.Hash(input));

            case HashType.Sha3Hash:
                Sha3Hash sha3 = new Sha3Hash();
                return(sha3.Hash(input));

            case HashType.Sha5Hash:
                Sha5Hash sha5 = new Sha5Hash();
                return(sha5.Hash(input));

            default:
                return("Cannot hash with this input");
            }
        }
示例#2
0
        private void WriteConnectionHeader(
            BinaryWriter writer,
            Sha1Hash infoHash,
            PeerId localPeerId)
        {
            // Length of protocol string
            writer.Write((byte)BitTorrentProtocol.Length);

            // Protocol
            writer.Write(BitTorrentProtocol.ToCharArray());

            // Reserved bytes
            var reservedBytes           = new byte[BitTorrentProtocolReservedBytes];
            var prepareHandshakeContext = new PrepareHandshakeContext(reservedBytes);

            foreach (var module in modules.Modules)
            {
                module.OnPrepareHandshake(prepareHandshakeContext);
            }
            writer.Write(prepareHandshakeContext.ReservedBytes);

            // Info hash
            writer.Write(infoHash.Value);

            // Peer ID
            writer.Write(localPeerId.Value.ToArray());

            writer.Flush();
        }
示例#3
0
        public byte[] Hash(HashType type, byte[] input)
        {
            switch (type)
            {
            case HashType.Md5Hash:
                Md5Hash md5 = new Md5Hash();
                return(md5.Hash(input));

            case HashType.Sha1Hash:
                Sha1Hash sha1 = new Sha1Hash();
                return(sha1.Hash(input));

            case HashType.Sha2Hash:
                Sha2Hash sha2 = new Sha2Hash();
                return(sha2.Hash(input));

            case HashType.Sha3Hash:
                Sha3Hash sha3 = new Sha3Hash();
                return(sha3.Hash(input));

            case HashType.Sha5Hash:
                Sha5Hash sha5 = new Sha5Hash();
                return(sha5.Hash(input));

            default:
                return(null);
            }
        }
        /// <summary>
        /// Create a new game
        /// </summary>
        /// <param name="game"></param>
        /// <returns></returns>
        public GameModel CreateGame(GameModel game)
        {
            if (game == null || !IsValid(game))
            {
                throw HttpResponseExceptionHelper.Create("Invalid format for specified new Game",
                                                         HttpStatusCode.BadRequest);
            }

            var username = UserToken.Username;

            game.HostHashId = UserToken.UserId;
            game.HashId     = Sha1Hash.GetSha1HashData(username + game.Name);

            // Add host to participants
            game.CurrentPlayerCount = 1;
            game.ParticipantsHashId.Add(UserToken.UserId);
            game.State = EnumsModel.GameState.Waiting;

            // insert in gameList
            lock (LockObj)
            {
                GameList.Add(game);
                return(ToPublic(game));
            }
        }
        public void HonorsAbortRequest()
        {
            string pw           = TestValues.GetPw(5);
            int    eventCounter = 0;
            var    logic        = new LogicImplementation();

            logic.CollisionFound  += (p) => { };
            logic.ProgressChanged += (c, l) => { eventCounter++; };
            var startTime = DateTime.Now;

            try
            {
                logic.StartSearchCollisionsTask(Sha1Hash.CalculateFromString(pw));
                startTime = DateTime.Now;
                while ((eventCounter == 0) && ((DateTime.Now - startTime).TotalMilliseconds < 500))
                {
                    Thread.Sleep(5);
                }
            }
            catch (Exception ex)
            {
                Assert.Fail($"Logic - \'StartSearchCollisionsTask\' method throws an exception: {ex.GetType().ToString()} - {ex.Message} ");
            }
            logic.AbortSearch();
            eventCounter = 0;
            startTime    = DateTime.Now;
            while ((eventCounter <= 1) && ((DateTime.Now - startTime).TotalMilliseconds < 200))
            {
                Thread.Sleep(5);
            }
            Assert.IsTrue((eventCounter <= 1), $"Logic - AbortSearch does not stop background Task.");
        }
示例#6
0
        public static void Main(string [] args)
        {
            var parser    = new CommandLineParser.CommandLineParser();
            var algorithm = new EnumeratedValueArgument <string> (
                'a',
                "algorithm",
                "available algorithms for computing hash, default to SHA1",
                new [] { Md2Hash.ALGORITHM_NAME,
                         Md5Hash.ALGORITHM_NAME,
                         Sha1Hash.ALGORITHM_NAME,
                         Sha256Hash.ALGORITHM_NAME,
                         Sha384Hash.ALGORITHM_NAME,
                         Sha512Hash.ALGORITHM_NAME });

            algorithm.DefaultValue = Sha1Hash.ALGORITHM_NAME;
            var source = new ValueArgument <string> (
                's',
                "source",
                "source to compute hash");

            source.Optional = false;
            var salt = new ValueArgument <string> (
                't',
                "salt",
                "salt for computing hash");
            var iterations = new ValueArgument <int> (
                'i',
                "iterations",
                "iterations when compute hash");

            iterations.DefaultValue = 1;
            parser.Arguments.AddRange(
                new Argument [] { algorithm, source, salt, iterations });

            parser.ParseCommandLine(args);

            if (!source.Parsed || string.IsNullOrEmpty(source.Value))
            {
                parser.ShowUsage();
                return;
            }

            SimpleHash hash = null;

            if (algorithm.Parsed)
            {
                hash = new SimpleHash(algorithm.Value, source.Value, salt.Value, iterations.Value);
            }
            if (hash == null)
            {
                hash = new Sha1Hash(source.Value, salt.Value, iterations.Value);
            }

            Console.WriteLine("algorithms  :" + hash.AlgorithmName);
            Console.WriteLine("source      :" + source.Value);
            Console.WriteLine("salt        :" + salt.Value);
            Console.WriteLine("iterations  :" + iterations.Value);
            Console.WriteLine("hash(hex)   :" + hash.ToHex());
            Console.WriteLine("hash(base64):" + hash.ToBase64());
        }
        public void DetectsCollision()
        {
            string pw      = TestValues.GetPw(2);
            string foundPw = string.Empty;
            var    logic   = new LogicImplementation();

            logic.CollisionFound  += (p) => { foundPw = p; };
            logic.ProgressChanged += (c, l) => { };
            try
            {
                logic.StartSearchCollisionsTask(Sha1Hash.CalculateFromString(pw));
                var startTime = DateTime.Now;
                while ((foundPw == string.Empty) && ((DateTime.Now - startTime).TotalMilliseconds < 1000))
                {
                    Thread.Sleep(5);
                }
            }
            catch (Exception ex)
            {
                Assert.Fail($"Logic - \'StartSearchCollisionsTask\' method throws an exception: {ex.GetType().ToString()} - {ex.Message} ");
            }
            logic.AbortSearch();
            Assert.IsFalse((foundPw == string.Empty), $"Logic - does not return a collision through its 'CollisionFound' event.");
            Assert.IsTrue((pw == foundPw), $"Logic - returns wrong value for a collision: \'{foundPw}\', expected: \'{pw}\'.");
        }
        public void HonorsReportInterval()
        {
            int    testInterval = 20;
            string pw           = TestValues.GetPw(5);
            ulong  pwCount      = 0;
            var    intervals    = new List <int>();
            var    previousTime = DateTime.Now;
            var    logic        = new LogicImplementation();
            var    cancelSource = new CancellationTokenSource();
            var    cancelToken  = cancelSource.Token;
            var    progress     = new Progress <ulong>((count) =>
            {
                pwCount    = count;
                DateTime t = DateTime.Now;
                intervals.Add((int)(t - previousTime).TotalMilliseconds);
                previousTime = t;
            });
            var collisionFound = new Progress <string>((result) => { });

            logic.ReportInterval = testInterval;
            var task      = Task.Run(() => { logic.SearchCollisions(Sha1Hash.CalculateFromString(pw), progress, collisionFound, cancelToken); });
            var startTime = DateTime.Now;

            while ((intervals.Count() < 4) && ((DateTime.Now - startTime).TotalMilliseconds < 500))
            {
                Thread.Sleep(5);
            }
            Assert.IsFalse((intervals.Count() == 0), $"SearchCollisions - does not report progress through its 'progress' object.");
            cancelSource.Cancel();
            intervals.RemoveAt(0);
            int interval = (intervals[0] + intervals[1] + intervals[2]) / 3;

            Assert.IsTrue((Math.Abs(testInterval - interval) < 20),
                          $"SearchCollisions - does not report progress at requested interval of {testInterval}ms, was {interval}ms.");
        }
示例#9
0
    // HandleLogonProof stuff
    public static BigInteger Getu(BigInteger A, BigInteger B)
    {
        Sha1Hash h = new Sha1Hash();

        h.Update(A);
        return(new BigInteger(h.Final(B)));
    }
        public void Setup()
        {
            writtenData = new List <Tuple <long, byte[]> >();

            Sha1Hash hash;

            using (var sha1 = SHA1.Create())
                hash = new Sha1Hash(sha1.ComputeHash(Enumerable.Repeat((byte)0, 50).ToArray()));

            var metainfo = new Metainfo("test",
                                        Sha1Hash.Empty,
                                        new[]
            {
                new ContainedFile("File1.txt", 100),
            },
                                        new[]
            {
                new Piece(0, 50, hash),
                new Piece(50, 50, hash),
            },
                                        new IEnumerable <Uri> [0],
                                        new byte[0]);

            var baseHandler = new Mock <IBlockDataHandler>();

            baseHandler.Setup(x => x.Metainfo)
            .Returns(metainfo);
            baseHandler.Setup(x => x.WriteBlockData(It.IsAny <long>(),
                                                    It.IsAny <byte[]>()))
            .Callback <long, byte[]>((offset, data) => writtenData.Add(Tuple.Create(offset, data)));

            pieceChecker = new PieceCheckerHandler(baseHandler.Object);
        }
示例#11
0
    public BigInteger GetM(string Username, BigInteger s, BigInteger A, BigInteger B, BigInteger K)
    {
        Sha1Hash sha;

        sha = new Sha1Hash();
        byte[] hash = sha.Final(N);

        sha = new Sha1Hash();
        byte[] ghash = sha.Final(g);

        for (int i = 0; i < 20; ++i)
        {
            hash[i] ^= ghash[i];
        }

        // TODO: do t2 and t4 need to be BigInts?  Could we just use the byte[]?
        BigInteger t3 = new BigInteger(hash);

        sha = new Sha1Hash();
        sha.Update(Username);
        BigInteger t4 = new BigInteger(sha.Final());

        sha = new Sha1Hash();
        sha.Update(t3);
        sha.Update(t4);
        sha.Update(s);
        sha.Update(A);
        sha.Update(B);
        return(new BigInteger(sha.Final(K)));
    }
示例#12
0
        public void Sha1Hash_GetHash_Null_3()
        {
            IHash hashAlgo = new Sha1Hash();

            Action action = () => hashAlgo.GetHash(null as FileInfo);

            action.Should().Throw <ArgumentNullException>();
        }
示例#13
0
        public void Sha1Hash_GetHash_Empty()
        {
            IHash hashAlgo = new Sha1Hash();

            Action action = () => hashAlgo.GetHash(string.Empty);

            action.Should().Throw <ArgumentNullException>();
        }
示例#14
0
 public AnnounceRequest(PeerId peerId,
                        long remaining,
                        Sha1Hash infoHash)
 {
     PeerId    = peerId;
     Remaining = remaining;
     InfoHash  = infoHash;
 }
        public void StartSearchCollisionsTask(Sha1Hash hash)
        {
            IProgress <string> foundCollision  = new Progress <string>((collision) => { CollisionFound?.Invoke(collision); });
            IProgress <ulong>  changedProgress = new Progress <ulong>((aantalPasswords) => { ProgressChanged?.Invoke(aantalPasswords, lengthTestedPassword); });

            cancelSource = new CancellationTokenSource();
            Task.Run(() => { SearchCollisions(hash, changedProgress, foundCollision, cancelSource.Token); });
        }
示例#16
0
    public static byte[] GetLogonHash(string Username, string Password)
    {
        Sha1Hash h  = new Sha1Hash();
        string   sI = String.Format("{0}:{1}", Username, Password.ToUpper());

        h.Update(sI);
        return(h.Final());
    }
示例#17
0
    public static BigInteger Getx(BigInteger Salt, byte[] LogonHash)
    {
        Sha1Hash h = new Sha1Hash();

        h.Update(Salt);
        h.Update(LogonHash);
        return(new BigInteger(h.Final()));
    }
示例#18
0
    public static byte[] GetM2(BigInteger A, BigInteger M, BigInteger K)
    {
        Sha1Hash h = new Sha1Hash();

        h.Update(A);
        h.Update(M);
        return(h.Final(K));
    }
示例#19
0
        public void Sha1Hash_GetHash_Valid_2()
        {
            IHash hashAlgo = new Sha1Hash();

            HashResult hashResult = hashAlgo.GetHash(Data.ExpectedHashFilePath);

            hashResult.Algorithm.Should().Be(Hashing.ExpectedSha1Algorithm);
            hashResult.Value.Should().Be(Hashing.ExpectedSha1Hash);
        }
        private Metainfo MockMetaInfo()
        {
            var fakeHash   = new Sha1Hash(new byte[20]);
            var fakePieces = new List <Piece>
            {
                new Piece(0, 100, fakeHash),
            };

            return(new Metainfo("Mock", fakeHash, new List <ContainedFile>(), fakePieces, new List <List <Uri> >(), new List <byte>()));
        }
        private void buttonSearchCollisions_Click(object sender, EventArgs e)
        {
            textBoxLength.Clear();
            textBoxCollision.Clear();
            textBoxCount.Clear();

            var hashPassword = Sha1Hash.GetFromHex(passwordHash);

            logicImpl.StartSearchCollisionsTask(hashPassword);
        }
示例#22
0
        public void Sha1Hash_GetHash_Valid_1()
        {
            IHash hashAlgo = new Sha1Hash();

            using FileStream fileStream = new(Data.ExpectedHashFilePath, FileMode.Open, FileAccess.Read, FileShare.Read);

            HashResult hashResult = hashAlgo.GetHash(fileStream);

            hashResult.Algorithm.Should().Be(Hashing.ExpectedSha1Algorithm);
            hashResult.Value.Should().Be(Hashing.ExpectedSha1Hash);
        }
示例#23
0
        public bool Compare(Sha1Hash hashX, Sha1Hash hashY)
        {
            bool result = false;

            if (hashX != null && hashY != null)
            {
                result = Compare(hashX.Value, hashY.Value);
            }

            return(result);
        }
 public AnnounceRequest(PeerId peerId,
                        long remaining,
                        long downloaded,
                        long uploaded,
                        Sha1Hash infoHash)
 {
     PeerId     = peerId;
     Remaining  = remaining;
     Downloaded = downloaded;
     Uploaded   = uploaded;
     InfoHash   = infoHash;
 }
        private void buttonCalculateHash_Click(object sender, EventArgs e)
        {
            string password = textBoxPassword.Text;

            password         = password.ToUpper();
            passwordHash     = Sha1Hash.CalculateFromString(password).ToString();
            textBoxHash.Text = passwordHash;

            textBoxPassword.Text           = password;
            buttonAbort.Enabled            = true;
            buttonSearchCollisions.Enabled = true;
        }
        public void CanStartSearchAfterAbort()
        {
            // start and abort a search.
            string pw           = TestValues.GetPw(5);
            string foundPw      = string.Empty;
            int    eventCounter = 0;
            var    logic        = new LogicImplementation();

            logic.CollisionFound  += (p) => { foundPw = p; };
            logic.ProgressChanged += (c, l) => { eventCounter++; };
            var startTime = DateTime.Now;

            try
            {
                logic.StartSearchCollisionsTask(Sha1Hash.CalculateFromString(pw));
                startTime = DateTime.Now;
                while ((eventCounter == 0) && ((DateTime.Now - startTime).TotalMilliseconds < 500))
                {
                    Thread.Sleep(5);
                }
            }
            catch (Exception ex)
            {
                Assert.Fail($"Logic - \'StartSearchCollisionsTask\' method throws an exception: {ex.GetType().ToString()} - {ex.Message} ");
            }
            logic.AbortSearch();
            eventCounter = 0;
            startTime    = DateTime.Now;
            while ((eventCounter <= 1) && ((DateTime.Now - startTime).TotalMilliseconds < 200))
            {
                Thread.Sleep(5);
            }
            Assert.IsTrue((eventCounter <= 1), $"Logic - AbortSearch does not stop background Task.");
            // and start a second one
            pw      = TestValues.GetPw(2);
            foundPw = string.Empty;
            try
            {
                logic.StartSearchCollisionsTask(Sha1Hash.CalculateFromString(pw));
                startTime = DateTime.Now;
                while ((foundPw == string.Empty) && ((DateTime.Now - startTime).TotalMilliseconds < 1000))
                {
                    Thread.Sleep(5);
                }
            }
            catch (Exception ex)
            {
                Assert.Fail($"Logic - \'StartSearchCollisionsTask\' method throws an exception when started after an abort request: {ex.GetType().ToString()} - {ex.Message} ");
            }
            Assert.IsFalse((foundPw == string.Empty), $"Logic - does not return a collision when started after an abort request.");
            logic.AbortSearch();
        }
示例#27
0
        private void SaveResumeDataAlert(Core.save_resume_data_alert a)
        {
            Interlocked.MemoryBarrier();
            TorrentHandle h  = null;
            BinaryWriter  bw = null;
            FileStream    fs = null;

            try
            {
                h = a.handle;
                using (TorrentInfo ti = h.torrent_file())
                    using (Sha1Hash hash = h.info_hash())
                    {
                        log.Debug("processing {0}", ti.name());
                        string newfilePath = ("./Fastresume/" + hash.ToString() + ".fastresume");
                        var    data        = Core.Util.bencode(a.resume_data);
                        fs = new FileStream(newfilePath, FileMode.OpenOrCreate);
                        bw = new BinaryWriter(fs);
                        bw.Write(data);
                        bw.Close();
                        log.Debug("done {0}", ti.name());
                    }
                //log.Debug(" for {0}", h.torrent_file().name());
                //string newfilePath = ("./Fastresume/" + h.info_hash().ToString() + ".fastresume");
                //var data = Core.Util.bencode(a.resume_data);
                //fs = new FileStream(newfilePath, FileMode.OpenOrCreate);
                //bw = new BinaryWriter(fs);
                //bw.Write(data);
                //bw.Close();
            }
            finally
            {
                if (!ReferenceEquals(null, h))
                {
                    h.Dispose();
                }
                if (!ReferenceEquals(null, bw))
                {
                    bw.Dispose();
                }
                if (!ReferenceEquals(null, fs))
                {
                    fs.Dispose();
                }
            }

            Interlocked.Decrement(ref outstanding_resume_data);
            if (outstanding_resume_data == 0 && no_more_resume)
            {
                no_more_data.Set();
            }
        }
示例#28
0
        void OnBCalcSha1Click(object sender, EventArgs e)
        {
            try
            {
                ShowStatusMessage(Str.cHashCalculating);

                if (_Sha1Main == null)
                {
                    _Sha1Main = new Sha1Alg();
                }

                //получаем количество значимых бит от пользователя и если оно корректно устанавливаем его,
                //иначе - работаем с количеством бит по умолчанию
                int userHashBitCount;

                if (int.TryParse(tbHashBitCount.Text, out userHashBitCount) &&
                    userHashBitCount >= cMinHashBitCount && userHashBitCount <= cMaxHashBitCount)
                {
                    HashBitCount = userHashBitCount;
                }
                else
                {
                    tbHashBitCount.Text = HashBitCount.ToString();
                }

                Stopwatch hashSW = new Stopwatch();
                hashSW.Start();                                  //запускаем замер времени выполнения

                _MainHash = _Sha1Main.GetHash(tbInputText.Text); //вычисляем хеш от содержимого текстбокса
                hashSW.Stop();                                   //останавливаем, независимо от результата

                if (_MainHash != null && !String.IsNullOrEmpty(_MainHash.Text))
                {
                    lSha1Hash.Text      = "0x" + _MainHash.Text;
                    lTruncSha1Hash.Text = "0x" + _Sha1Main.GetTruncateHash(_MainHash.Value).Text;
                    lSha1Time.Text      = hashSW.Elapsed.ToString();

                    _MainText       = tbInputText.Text;
                    _Sha1Calculated = true;                             //указываем что в _Sha1Main посчитанный хеш и можно искать коллизии

                    ShowStatusMessage(Str.cHashCalcEnd);
                }
                else
                {
                    ShowStatusMessage(Str.cCantCalcHash, true);
                }
            }
            catch (Exception ex)
            {
                ShowStatusMessage(Str.cExceptionHappened + ex.Message, true);
            }
        }
        public void DoAuthSession()
        {
            try
            {
                PacketOut packet = new PacketOut(WorldServerOpCode.CMSG_AUTH_SESSION);


                Sha1Hash sha = new Sha1Hash();
                sha.Update(mUsername);
                sha.Update(new byte[4]); // t
                sha.Update(ClientSeed);
                sha.Update(ServerSeed);
                sha.Update(mKey);

                byte[] Digest = sha.Final();

                packet.Write((UInt32)Config.Version.build);
                packet.Write((UInt32)0);
                packet.Write(mUsername);
                packet.Write((UInt32)0);
                packet.Write(ClientSeed);
                packet.Write((UInt64)0);
                packet.Write(Digest);



                bool WantToCrash = false;
                if (WantToCrash)
                {
                    byte[] addons  = { (byte)0x00 };
                    byte[] buffer2 = mClient.Shared.Compression.Compress(addons);
                    UInt32 Size    = (UInt32)addons.Length;
                    packet.Write(Size);
                    packet.Write(buffer2);
                }
                else
                {
                    byte[] addon_data = { 0x56, 0x01, 0x00, 0x00, 0x78, 0x9c, 0x75, 0xcc, 0xbd, 0x0e, 0xc2, 0x30, 0x0c, 0x04, 0xe0, 0xf2, 0x1e, 0xbc, 0x0c, 0x61, 0x40, 0x95, 0xc8, 0x42, 0xc3, 0x8c, 0x4c, 0xe2, 0x22, 0x0b, 0xc7, 0xa9, 0x8c, 0xcb, 0x4f, 0x9f, 0x1e, 0x16, 0x24, 0x06, 0x73, 0xeb, 0x77, 0x77, 0x81, 0x69, 0x59, 0x40, 0xcb, 0x69, 0x33, 0x67, 0xa3, 0x26, 0xc7, 0xbe, 0x5b, 0xd5, 0xc7, 0x7a, 0xdf, 0x7d, 0x12, 0xbe, 0x16, 0xc0, 0x8c, 0x71, 0x24, 0xe4, 0x12, 0x49, 0xa8, 0xc2, 0xe4, 0x95, 0x48, 0x0a, 0xc9, 0xc5, 0x3d, 0xd8, 0xb6, 0x7a, 0x06, 0x4b, 0xf8, 0x34, 0x0f, 0x15, 0x46, 0x73, 0x67, 0xbb, 0x38, 0xcc, 0x7a, 0xc7, 0x97, 0x8b, 0xbd, 0xdc, 0x26, 0xcc, 0xfe, 0x30, 0x42, 0xd6, 0xe6, 0xca, 0x01, 0xa8, 0xb8, 0x90, 0x80, 0x51, 0xfc, 0xb7, 0xa4, 0x50, 0x70, 0xb8, 0x12, 0xf3, 0x3f, 0x26, 0x41, 0xfd, 0xb5, 0x37, 0x90, 0x19, 0x66, 0x8f };
                    packet.Write(addon_data);
                }

                Send(packet);


                mCrypt = new PacketCrypt(mKey);
                mCrypt.Init();
            }
            catch (Exception e)
            {
                Log.WriteLine(LogType.Error, e.StackTrace);
            }
        }
示例#30
0
        public Sha1Hash GetHash(string text, Encoding enc)
        {
            Sha1Hash result = new Sha1Hash();

            byte[] buffer = enc.GetBytes(text);    //преобразуем переданный текст в набор байт с учетом кодировки

            InitializeState();                     //задаем начальные значения
            HashData(buffer, 0, buffer.Length);    //вычисляем все блоки кроме последнего

            result.Value     = EndHash();          //вычисляем последний блок и фиксируем результат
            result.ByteCount = result.Value.Length;

            return(result);
        }