Ejemplo n.º 1
0
        private static int Hash(string fileName)
        {
            try
            {
                byte[] hash;

                using (EnhancedStream es = new EnhancedFileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    hash = MD5Hasher.Compute(es, es.Length);
                }

                using (StreamWriter writer = new StreamWriter(fileName + ".md5", false, Helper.AnsiEncoding))
                {
                    writer.WriteLine("MD5={0}", Helper.ToHex(hash));
                }

                File.Copy(fileName, fileName + ".setup");

                return(0);
            }
            catch (Exception e)
            {
                Program.Error("Error ({0}): {1}", e.GetType().Name, e.Message);
                return(1);
            }
        }
Ejemplo n.º 2
0
        private void CompareFiles(string path1, string path2)
        {
            EnhancedFileStream es1 = null;
            EnhancedFileStream es2 = null;

            try
            {
                es1 = new EnhancedFileStream(path1, FileMode.Open, FileAccess.Read);
                es2 = new EnhancedFileStream(path2, FileMode.Open, FileAccess.Read);

                Assert.AreEqual(es1.Length, es2.Length);
                CollectionAssert.AreEqual(MD5Hasher.Compute(es1, es1.Length), MD5Hasher.Compute(es2, es2.Length));
            }
            finally
            {
                if (es1 != null)
                {
                    es1.Close();
                }

                if (es2 != null)
                {
                    es2.Close();
                }
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Computes an MD5 hash code for the log entry
        /// </summary>
        /// <param name="extension">The extended entry information (or <c>null</c>).</param>
        /// <param name="entryType">The log entry type.</param>
        /// <param name="message">The log message (or <c>null</c>).</param>
        /// <param name="e">The logged exception (or <c>null</c>).</param>
        /// <returns>The computed hash.</returns>
        private static MD5Key ComputeMD5Hash(ISysLogEntryExtension extension, SysLogEntryType entryType, string message, Exception e)
        {
            StringBuilder sb = new StringBuilder(1024);

            if (extension != null)
            {
                sb.Append(extension.Format());
            }

            sb.Append('\t');

            sb.Append(entryType.ToString());
            sb.Append('\t');

            if (message != null)
            {
                sb.Append(message);
            }

            sb.Append('\t');

            if (e != null)
            {
                sb.Append(e.GetType().FullName);
                sb.Append('\t');
                sb.Append(e.Message);
                sb.Append('\t');
                sb.Append(e.StackTrace.ToString());
            }

            return(new MD5Key(MD5Hasher.Compute(sb.ToString())));
        }
Ejemplo n.º 4
0
        private void btnEnter_Click(object sender, EventArgs e)
        {
            Account account = new Account();

            account.Login    = txtLogin.Text.Trim();
            account.Password = MD5Hasher.GetHash(txtPassword.Text.Trim());

            if (account.Login == adminLogin && account.Password == adminPassword)
            {
                FmAdminMenu adminMenu = new FmAdminMenu();
                adminMenu.Show();
                this.Hide();

                return;
            }

            Employee employee = AccountDAO.SearchEmployee(account);


            if (employee != null)
            {
                FmMainMenu mainMenu = new FmMainMenu(employee);
                mainMenu.Show();
                this.Hide();

                return;
            }

            string loginErrorMessage = $"Ошибка входа в систему.{Environment.NewLine}Неверные имя пользователя или пароль.";

            MessageBox.Show(loginErrorMessage, "Ошибка входа.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
Ejemplo n.º 5
0
        private void UpdateEmployee(Employee employee)
        {
            employee.Passport          = txtPassport.Text;
            employee.FullName          = txtFullName.Text;
            employee.Phone             = txtPhone.Text;
            employee.Position          = (Position)ctlPosition.SelectedItem;
            employee.DrivingCategories = new List <DrivingCategory>();
            for (int i = 0; i < ctlDrivingCategories.Items.Count; i++)
            {
                if (ctlDrivingCategories.GetSelected(i))
                {
                    employee.DrivingCategories.Add((DrivingCategory)ctlDrivingCategories.Items[i]);
                }
            }

            if (!string.IsNullOrEmpty(txtLogin.Text))
            {
                if (employee.Account == null)
                {
                    employee.Account = new Account();
                }

                employee.Account.Login = txtLogin.Text;

                if (!string.IsNullOrEmpty(txtPassword.Text))
                {
                    employee.Account.Password = MD5Hasher.GetHash(txtPassword.Text);
                }
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Closes the package, optionally leaving the output stream open.
        /// </summary>
        /// <param name="leaveOutputOpen"><c>true</c> to leave the output stream open.</param>
        public void Close(bool leaveOutputOpen)
        {
            if (packageOut != null)
            {
                // Append the terminating entry.

                new PackageEntry(this).Serialize(packageOut);

                // Before we close the package, we need to compute the MD5
                // hash of everything after the header in the output stream
                // and update the hash in the header.

                var header = new PackageHeader();

                packageOut.Position = cbHeader;
                header.Hash         = MD5Hasher.Compute(packageOut, packageOut.Length - cbHeader);

                packageOut.Position = 0;
                header.Seralize(packageOut);

                if (!leaveOutputOpen)
                {
                    packageOut.Close();
                }

                packageOut = null;
            }

            if (packageIn != null)
            {
                packageIn.Close();
                packageIn = null;
            }
        }
Ejemplo n.º 7
0
        private static void AddMessage(SlackHistoryViewerDbContext dbContext, Message message, string channelId)
        {
            var newMessage = new Messages();

            newMessage.MessageId = MD5Hasher.GetMd5Hash(message.User + message.TimeStamp);

            var idUser = dbContext.Users
                         .Where(u => u.UserId == message.User)
                         .Select(u => u.Id)
                         .FirstOrDefault();

            if (idUser == 0)
            {
                var botId = dbContext.Users
                            .Where(u => u.UserId == AppSettings.Instance.UnknownBotId)
                            .Select(u => u.Id)
                            .FirstOrDefault();

                idUser = botId;
            }

            newMessage.UserId = idUser;

            var idChannel = dbContext.Channels
                            .Where(c => c.ChannelId == channelId)
                            .Select(c => c.Id)
                            .FirstOrDefault();

            newMessage.ChannelId = idChannel;
            newMessage.JsonData  = JsonConvert.SerializeObject(message);

            dbContext.Messages.Add(newMessage);
        }
Ejemplo n.º 8
0
        public void WebTransferFile_UploadMD5()
        {
            // Test the file upload with MD5 validation scenario and
            // also test appending with position.

            WebTransferFile transferFile;
            Guid            id;

            byte[] block1 = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            byte[] block2 = new byte[] { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
            byte[] block;
            long   pos;

            ClearFolder();

            // Create a file

            id           = Guid.NewGuid();
            transferFile = new WebTransferFile(id, folder, new Uri("http://test.com"), ".pdf", true, true);
            Assert.AreEqual(id, transferFile.ID);
            Assert.IsTrue(transferFile.IsUploading);
            Assert.IsTrue(File.Exists(transferFile.Path + WebTransferCache.UploadExtension));
            Assert.AreEqual(new Uri(new Uri("http://test.com"), transferFile.ID.ToString("D") + ".pdf"), transferFile.Uri);

            // Append the first block

            pos = 0;
            transferFile.Append(pos, block1);

            // Append it again to simulate a duplicate

            transferFile.Append(pos, block1);
            pos += block1.Length;

            // Open an existing file

            transferFile = new WebTransferFile(id, folder, new Uri("http://test.com"), ".pdf", false, true);
            Assert.AreEqual(id, transferFile.ID);
            Assert.IsTrue(transferFile.IsUploading);
            Assert.IsTrue(File.Exists(transferFile.Path + WebTransferCache.UploadExtension));
            Assert.AreEqual(new Uri(new Uri("http://test.com"), transferFile.ID.ToString("D") + ".pdf"), transferFile.Uri);

            // Append the second block

            transferFile.Append(pos, block2);

            // Complete the upload and verify the file contents.

            transferFile.Commit(MD5Hasher.Compute(Helper.Concat(block1, block2)));
            Assert.AreEqual(id, transferFile.ID);
            Assert.IsFalse(transferFile.IsUploading);
            Assert.IsTrue(File.Exists(transferFile.Path));
            Assert.AreEqual(new Uri(new Uri("http://test.com"), transferFile.ID.ToString("D") + ".pdf"), transferFile.Uri);

            using (var stream = transferFile.GetStream())
            {
                block = stream.ReadBytes((int)stream.Length);
                CollectionAssert.AreEqual(Helper.Concat(block1, block2), block);
            }
        }
Ejemplo n.º 9
0
        public ActionResult Login(LoginModel logon)
        {
            if (ModelState.IsValid)
            {
                var dbUser = db.Users.FirstOrDefault(u => u.Name == logon.Name);

                if (dbUser == null ||
                    dbUser.Password != MD5Hasher.ComputeHash(logon.Password))
                {
                    ModelState.AddModelError("", "Wrong login or password!");
                    return(View(logon));
                }
                else if (dbUser != null &&
                         dbUser.Password == MD5Hasher.ComputeHash(logon.Password) &&
                         string.Equals(dbUser.Name, logon.Name))
                {
                    if (logon.Name == "admin")
                    {
                        Session["IsAdmin"] = true;
                    }
                    else
                    {
                        Session["IsAdmin"] = null;
                    }
                    Session["Name"] = logon.Name;
                    Session["Id"]   = dbUser.Id;

                    return(RedirectToAction("Index", "Home"));
                }
            }

            return(View(logon));
        }
Ejemplo n.º 10
0
        public ActionResult Register(RegisterModel register)
        {
            if (ModelState.IsValid)
            {
                var dbUser = db.Users.FirstOrDefault(u => u.Name == register.Name);

                if (dbUser == null || !string.Equals(dbUser.Name, register.Name))
                {
                    register.Password = MD5Hasher.ComputeHash(register.Password);

                    db.Users.Add(new User
                    {
                        Name     = register.Name,
                        Password = register.Password
                    });
                    db.SaveChanges();

                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    ModelState.AddModelError("", "Such username exists!");
                    return(View(register));
                }
            }

            return(View(register));
        }
Ejemplo n.º 11
0
        public ActionResult Login(LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                var password = MD5Hasher.Encrypt(model.password, "vgrad");
                var user     = db.Users.Where(s => s.Email.Equals(model.Email, StringComparison.CurrentCultureIgnoreCase) && s.Password == password).FirstOrDefault();
                if (user == null)
                {
                    TempData["msg"] = "Invalid Email/Password!";
                    return(View(model));
                }
                Session["UserName"] = user.Name;
                Session["UserType"] = user.Type;
                Session["UserId"]   = user.UserId;
                Session["Email"]    = user.Email;
                switch (user.Type)
                {
                case UserType.Administrator:
                    return(RedirectToAction("Index", "Users"));

                case UserType.Coordinator:
                    return(RedirectToAction("Index", "Projects"));

                case UserType.Student:
                    return(RedirectToAction("BasicInformation", "Home"));

                default:
                    return(RedirectToAction(""));
                }
            }
            return(View(model));
        }
Ejemplo n.º 12
0
        static void Main(string[] args)
        {
            string basePath = $"{Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName}\\Data";

            List <string> top100Passwords = File.ReadAllLines($"{basePath}\\top_100.txt")
                                            .SelectMany(line => line.Split(" ", StringSplitOptions.RemoveEmptyEntries).TakeLast(1).Select(s => s.Trim()))
                                            .ToList();
            List <string> top100000Passwords = File.ReadAllLines($"{basePath}\\top_100000.txt")
                                               .Select(line => line.Trim())
                                               .ToList();
            var passwordGenerator = new PasswordsGenerator(top100Passwords, top100000Passwords);

            int passwordsPerFile = 100_000;

            BaseHasher hasher = new MD5Hasher();

            //passwordGenerator.GeneratePasswords(passwordsCount: passwordsPerFile)
            //    .Select(p => hasher.GetHashedRecord(p))
            //    .WriteListToCsvFile($"{basePath}\\md5_hashed.csv");

            //hasher = new SHA1Hasher();
            //passwordGenerator.GeneratePasswords(passwordsCount: passwordsPerFile)
            //    .Select(p => hasher.GetHashedRecord(p))
            //    .WriteListToCsvFile($"{basePath}\\sha1_hashed.csv");

            hasher = new Argon2idHasher();
            passwordGenerator.GeneratePasswords(passwordsCount: passwordsPerFile)
            .ForEach(p => hasher.GetHashedRecord(p).AppendRecordToCsvFile($"{basePath}\\argon2id_hashed.csv"));
        }
Ejemplo n.º 13
0
        public ActionResult Create([Bind(Include = "UserId,Name,Email,Password,Type")] User user)
        {
            if (Session["UserId"] == null)
            {
                return(RedirectToAction("Login", "Home"));
            }
            else if (Session["UserType"].ToString() != UserType.Administrator.ToString() && Session["UserType"].ToString() != UserType.Coordinator.ToString())
            {
                TempData["msg"] = "You don't have enough rights";
                return(RedirectToAction("Login", "Home"));
            }
            if (ModelState.IsValid)
            {
                var ExistingUser = db.Users.Where(s => s.Email.Equals(user.Email, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
                if (ExistingUser != null)
                {
                    TempData["msg"] = "Email already registered!";
                    return(View(user));
                }

                TempData["msg"] = "New User Added";
                user.Password   = MD5Hasher.Encrypt(user.Password, "vgrad");
                db.Users.Add(user);
                db.SaveChanges();
                TempData["msg"] = "User Created";
                return(RedirectToAction("Index"));
            }

            return(View(user));
        }
Ejemplo n.º 14
0
        private static Hasher CreateHasher(int crypto)
        {
            Hasher hasher = null;

            switch (crypto)
            {
            case (int)HashName.MD5:
                hasher = new MD5Hasher();
                break;

            case (int)HashName.SHA1:
                hasher = new SHA1Hasher();
                break;

            case (int)HashName.SHA256:
                hasher = new SHA256Hasher();
                break;

            case (int)HashName.SHA384:
                hasher = new SHA384Hasher();
                break;

            case (int)HashName.SHA512:
                hasher = new SHA512Hasher();
                break;
            }
            return(hasher);
        }
Ejemplo n.º 15
0
        public ServiceResult Register(UserViewModel viewModel)
        {
            return(Insert(viewModel));

            // remove this if the above code works
            ServiceResult serviceResult = new ServiceResult();

            viewModel.Password = MD5Hasher.ComputeHash(viewModel.Password);

            try
            {
                viewModel.RowId = Guid.NewGuid().ToString();
                var user = MapperHelper.Instance.Map <UserViewModel, User>(viewModel);
                user.Created = DateTime.Now;

                userRepository.Insert(user);

                serviceResult.Success = true;
                serviceResult.Messages.Add(Error.GetErrorMessage(Error.CorrectTransaction));
            }
            catch (Exception ex)
            {
                serviceResult.LogError(ex);
            }

            return(serviceResult);
        }
Ejemplo n.º 16
0
        public ActionResult Register(RegisterModel register)
        {
            if (ModelState.IsValid)
            {
                var dbUser = db.Users.FirstOrDefault(u => u.Name == register.Name);

                if (dbUser == null || !string.Equals(dbUser.Name, register.Name))
                {
                    register.Password = MD5Hasher.ComputeHash(register.Password);

                    db.Users.Add(new User
                    {
                        Name     = register.Name,
                        Password = register.Password,
                        IsActive = false
                    });
                    db.SaveChanges();

                    Session["Notification"] = "Your registration is accepted. Wait for review of its portal administrator. Try to log in later, when it is confirmed.";
                    return(RedirectToAction("Notification", "Accounts"));
                }
                else
                {
                    ModelState.AddModelError("", "Such username exists!");
                    return(View(register));
                }
            }

            return(View(register));
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Writes a message file.
        /// </summary>
        /// <param name="path">The file path.</param>
        /// <param name="msg">The message.</param>
        /// <param name="msgInfo">The message metadata.</param>
        internal void WriteMessage(string path, QueuedMsg msg, QueuedMsgInfo msgInfo)
        {
            byte[] md5Hash;

            using (var fsMsg = new EnhancedFileStream(path, FileMode.Create, FileAccess.ReadWrite))
            {
                // Write the file header

                fsMsg.WriteInt32(MsgMagic);         // Magic Number
                fsMsg.WriteInt32(0);                // Format Version
                fsMsg.WriteInt32(0);                // Reserved
                fsMsg.WriteBytesNoLen(md5Zeros);    // MD5 hash placeholder

                // Write the message body.

                fsMsg.WriteBytes32(msg.BodyRaw);

                // Write the metadata.

                fsMsg.WriteString16(msgInfo.ToString());

                // Compute and save the MD5 hash

                fsMsg.Position = MsgHeaderSize;
                md5Hash        = MD5Hasher.Compute(fsMsg, fsMsg.Length - fsMsg.Position);
                fsMsg.Position = MsgMD5Offset;
                fsMsg.WriteBytesNoLen(md5Hash);
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Decompress the list of files, verify the CRC and save to disk
        /// </summary>
        public void extractAndVerify(object arg)
        {
            KeyValuePair <ExtractorConfiguration, Dictionary <string, byte[]> > compressedFiles =
                (KeyValuePair <ExtractorConfiguration, Dictionary <string, byte[]> >)arg;

            GZip      gzip                = new GZip();
            MD5Hasher md5                 = new MD5Hasher();
            FileDao   fileDao             = new FileDao();
            ExtractorConfiguration config = compressedFiles.Key;

            foreach (string s in compressedFiles.Value.Keys)
            {
                try
                {
                    DataTable decompressedObject = (DataTable)gzip.decompress(compressedFiles.Value[s]);
                    string    hash = md5.calculateMD5(decompressedObject);
                    if (!String.Equals(s, hash, StringComparison.CurrentCultureIgnoreCase))
                    {
                        // TODO - IMPORTANT!!! NEED TO DO SOMETHING HERE - DON'T PROCEED!!!
                    }

                    fileDao.saveToFile(decompressedObject, config.ExtractMode);
                }
                catch (Exception)
                {
                    // TODO - very important we report this some how!!!
                }
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Updates a message file's metadata.
        /// </summary>
        /// <param name="path">The file path.</param>
        /// <param name="msgInfo">The message metadata.</param>
        internal void WriteMessageMetadata(string path, QueuedMsgInfo msgInfo)
        {
            using (var fsMsg = new EnhancedFileStream(path, FileMode.Open, FileAccess.ReadWrite))
            {
                // Seek past the message's header and body.

                int    cbBody;
                byte[] md5Hash;

                fsMsg.Position = MsgHeaderSize;
                cbBody         = fsMsg.ReadInt32();
                fsMsg.Position = fsMsg.Position + cbBody;

                // Write the metadata and truncate the file.

                fsMsg.WriteString16(msgInfo.ToString());
                fsMsg.SetLength(fsMsg.Position);

                // Regenerate the MD5 Hash

                fsMsg.Position = MsgMD5Offset + MD5Hasher.DigestSize;
                md5Hash        = MD5Hasher.Compute(fsMsg, fsMsg.Length - fsMsg.Position);
                fsMsg.Position = MsgMD5Offset;
                fsMsg.WriteBytesNoLen(md5Hash);
            }
        }
Ejemplo n.º 20
0
        private void btnok_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(Txtname.Text) || string.IsNullOrWhiteSpace(Txtpassword.Text))
                {
                    MessageBox.Show(@"نام کاربری و رمز عبور را وارد نمایید");
                    return;
                }

                var user = GlobalService.Repository.GetUser(Txtname.Text.ToInt(),
                                                            MD5Hasher.ComputeHashMIS(Txtpassword.Text));
                if (user != null)
                {
                    if (user.IsActive == false)
                    {
                        MessageBox.Show(@"کاربر غیرفعال است");
                        return;
                    }
                    GlobalService.LoginUser = user;
                    this.DialogResult       = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    MessageBox.Show(@"نام کاربری یا رمز عبور اشتباه است");
                }
            }
            catch (Exception ex)
            {
                ErrorLog.SaveLog(ex);
            }
        }
Ejemplo n.º 21
0
        public ActionResult Authorize(string email, string password)
        {
            var pwd = MD5Hasher.Hash(password);

            if (IfUserExists(email, pwd))
            {
                var user  = db.User.Where(a => a.Email == email && a.Password == pwd).FirstOrDefault();
                var token = CreateToken(email);
                var date  = DateTime.Now;

                db.Auth.Add(new Auth {
                    UserID = user.ID, Token = token, Date = date
                });
                db.SaveChanges();
                HttpCookie cookie = new HttpCookie("User");
                cookie["role"]  = user.RoleID.ToString();
                cookie["token"] = token;
                cookie["user"]  = user.Name;
                cookie["id"]    = user.ID.ToString();
                cookie.Expires  = DateTime.Now.AddHours(8);
                Response.Cookies.Add(cookie);
            }

            return(Redirect("~/Index"));
        }
Ejemplo n.º 22
0
        public ServiceResult Login(UserViewModel viewModel)
        {
            ServiceResult serviceResult = new ServiceResult();

            viewModel.Password = MD5Hasher.ComputeHash(viewModel.Password);

            try
            {
                var user = ((List <User>)userRepository.
                            GetAll(i => i.Username == viewModel.Username &&
                                   i.Password == viewModel.Password).Data).FirstOrDefault();

                if (user != null)
                {
                    user.LastAccessDate = DateTime.Now;

                    userRepository.Update(user);
                }

                serviceResult.Success      = true;
                serviceResult.ResultObject = MapperHelper.Instance.Map <User, UserViewModel>(user);
                serviceResult.Messages.Add(Error.GetErrorMessage(Error.CorrectTransaction));
            }
            catch (Exception ex)
            {
                serviceResult.LogError(ex);
            }

            return(serviceResult);
        }
Ejemplo n.º 23
0
        public void Hashers_MD5()
        {
            EnhancedMemoryStream ms;

            byte[] data;
            byte[] digest1, digest2;

            digest1 = MD5Hasher.Compute(new byte[] { 0, 1, 2, 3 }, 0, 4);
            Assert.AreEqual(16, digest1.Length);
            Assert.AreEqual(16, MD5Hasher.DigestSize);

            digest2 = MD5Hasher.Compute(new byte[] { 1, 1, 2, 3 }, 0, 4);
            Assert.AreNotEqual(digest1, digest2);

            digest1 = MD5Hasher.Compute(new byte[0]);
            Assert.AreEqual(16, digest1.Length);
            Assert.AreEqual(16, MD5Hasher.DigestSize);

            digest1 = MD5Hasher.Compute(new byte[] { 0, 1, 2, 3 });
            ms      = new EnhancedMemoryStream();

            ms.Seek(0, SeekOrigin.Begin);
            ms.Write(new byte[] { 0, 1, 2, 3 }, 0, 4);
            ms.Seek(0, SeekOrigin.Begin);
            digest2 = MD5Hasher.Compute(ms, 4);
            CollectionAssert.AreEqual(digest1, digest2);
            Assert.AreEqual(16, digest2.Length);
            Assert.AreEqual(0, ms.Position);

            data = new byte[2048];
            for (int i = 0; i < data.Length; i++)
            {
                data[i] = (byte)i;
            }

            digest1 = MD5Hasher.Compute(data);

            ms.Seek(0, SeekOrigin.Begin);
            ms.Write(data, 0, data.Length);
            ms.Seek(0, SeekOrigin.Begin);

            digest2 = MD5Hasher.Compute(ms, data.Length);
            CollectionAssert.AreEqual(digest1, digest2);
            Assert.AreEqual(16, digest2.Length);
            Assert.AreEqual(0, ms.Position);

            digest1 = MD5Hasher.Compute("hello");
            digest2 = MD5Hasher.Compute("world");
            CollectionAssert.AreNotEqual(digest1, digest2);
            CollectionAssert.AreEqual(digest1, MD5Hasher.Compute("hello"));

            // These really aren't very good tests for folding but
            // at least they'll verify that it doesn't crash

            Assert.AreEqual(MD5Hasher.FoldOnce(new byte[] { 0, 1, 2, 3 }), MD5Hasher.FoldOnce(new byte[] { 0, 1, 2, 3 }));
            Assert.AreNotEqual((object)MD5Hasher.FoldOnce(new byte[] { 1, 1, 2, 3 }), (object)MD5Hasher.FoldOnce(new byte[] { 0, 1, 2, 3 }));
            Assert.AreEqual(MD5Hasher.FoldTwice(new byte[] { 0, 1, 2, 3 }), MD5Hasher.FoldTwice(new byte[] { 0, 1, 2, 3 }));
            Assert.AreNotEqual(MD5Hasher.FoldTwice(new byte[] { 1, 1, 2, 3 }), MD5Hasher.FoldTwice(new byte[] { 0, 1, 2, 3 }));
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Reads the metadata from a message file.
        /// </summary>
        /// <param name="msgID">The message ID.</param>
        /// <param name="path">Fully qualified path to the message file.</param>
        /// <returns>The <see cref="QueuedMsgInfo" />.</returns>
        internal QueuedMsgInfo ReadMessageMetadata(Guid msgID, string path)
        {
            QueuedMsgInfo msgInfo;
            int           cbBody;

            byte[] md5Hash;
            long   savePos;

            using (var fsMsg = new EnhancedFileStream(path, FileMode.Open, FileAccess.ReadWrite))
            {
                try
                {
                    // Read the message file header

                    if (fsMsg.ReadInt32() != MsgMagic)      // Magic Number
                    {
                        throw new Exception();
                    }

                    if (fsMsg.ReadInt32() != 0)             // Format Version
                    {
                        throw new Exception();
                    }

                    fsMsg.ReadInt32();                      // Reserved

                    // Verify that the MD5 hash saved in then file matches the
                    // hash computed for the remainder of the file as it exists
                    // right now.

                    md5Hash = fsMsg.ReadBytes(MD5Hasher.DigestSize);
                    savePos = fsMsg.Position;

                    if (!Helper.ArrayEquals(md5Hash, MD5Hasher.Compute(fsMsg, fsMsg.Length - fsMsg.Position)))
                    {
                        throw new FormatException(string.Format("Message file [{0}] is corrupt. MD5 digests do not match.", path));
                    }

                    fsMsg.Position = savePos;

                    // Skip over the message body data

                    cbBody         = fsMsg.ReadInt32();
                    fsMsg.Position = fsMsg.Position + cbBody;

                    // Read the metadata and add the provider specific information

                    msgInfo              = new QueuedMsgInfo(fsMsg.ReadString16());
                    msgInfo.PersistID    = msgInfo.ID;
                    msgInfo.ProviderData = path;

                    return(msgInfo);
                }
                catch
                {
                    throw new FormatException(string.Format("Bad message file [{0}].", path));
                }
            }
        }
Ejemplo n.º 25
0
        public Session GenerateSession(long personId, string deviceCode)
        {
            var sessionKey = MD5Hasher.GetMd5Hash(Guid.NewGuid().ToString());
            var session    = new Session(deviceCode, sessionKey, personId, 87360);          // 10 Years

            _apiSessionRepository.Save(session);
            return(session);
        }
Ejemplo n.º 26
0
 private void GetFileInfo(string fileName, out int size, out byte[] md5)
 {
     using (var es = new EnhancedFileStream(tempFolder + "\\" + fileName, FileMode.Open, FileAccess.Read))
     {
         size = (int)es.Length;
         md5  = MD5Hasher.Compute(es, size);
     }
 }
        public void canGetMD5HasFromFile()
        {
            MD5Hasher hasher   = new MD5Hasher();
            string    fileName = @"C:\Windows\notepad.exe";

            string hash = hasher.GetFileHash(fileName);

            Assert.IsTrue(hash != null);
        }
        public void canGetMD5FromText()
        {
            MD5Hasher hasher = new MD5Hasher();
            string    text   = "Some text to hash in MD5 mode";

            string hash = hasher.HashText(text);

            Assert.IsTrue(hash != null);
            Assert.AreNotEqual(text, hash);
        }
Ejemplo n.º 29
0
        protected override void Seed(GalleryContext context)
        {
            context.Users.Add(new User
            {
                Name     = "admin",
                Password = MD5Hasher.ComputeHash("admin")
            });

            base.Seed(context);
        }
Ejemplo n.º 30
0
        public IHttpActionResult Post()
        {
            var httpRequest = HttpContext.Current.Request;


            string fileName = null;

            //var  = httpRequest.Params["naam"];
            //var collection = httpRequest.Params["studentNumber"];

            try
            {
                fileName = httpRequest.Files[0].FileName;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(BadRequest("Could not be uploaded:" + e.Message));
            }


            if (!fileName.IsEmpty())
            {
                HttpPostedFile postedFile       = httpRequest.Files[0];
                int            postedFileLength = postedFile.ContentLength;
                byte[]         input            = new byte[postedFileLength];

                Stream mystream = postedFile.InputStream;
                mystream.Read(input, 0, postedFileLength);


                Exam exam = new Exam();
                exam.Bytes = input;
                string hash = MD5Hasher.CalculateHash(input);
                exam.Md5 = hash;

                exam = _examRepo.AddExam(exam);

                Student student = new Student();
                student.Name          = httpRequest.Params["naam"];
                student.FirstName     = "demo";
                student.ExamenHash    = hash;
                student.StudentNumber = httpRequest.Params["studentNumber"];
                student.Datetime      = DateTime.Now.ToString();
                student.FileName      = "webExamen.zip";
                student.ExamenId      = exam.Id;


                _studentRepo.AddStudent(student);
                //return Ok($"File {fileName} Uploaded");
                return(Ok(hash));
            }

            return(BadRequest("Could not be uploaded"));
        }