public static HashCollection GenerateHashes(this Stream stream)
        {
            var buffer       = new byte[BUFFER_SIZE];
            var md5Worker    = new HashWorker(HashTypes.MD5);
            var sha1Worker   = new HashWorker(HashTypes.SHA1);
            var sha256Worker = new HashWorker(HashTypes.SHA256);
            var sha512Worker = new HashWorker(HashTypes.SHA512);


            Task.Run(() =>
            {
                var bRead = 0;
                do
                {
                    bRead = stream.Read(buffer, 0, buffer.Length);

                    var tasks = new List <Task>
                    {
                        Task.Run(() => md5Worker.GenerateIncrementalHash(buffer, bRead)),
                        Task.Run(() => sha1Worker.GenerateIncrementalHash(buffer, bRead)),
                        Task.Run(() => sha256Worker.GenerateIncrementalHash(buffer, bRead)),
                        Task.Run(() => sha512Worker.GenerateIncrementalHash(buffer, bRead))
                    };

                    Task.WaitAll(tasks.ToArray());
                } while (bRead > 0);
            }).Wait();


            var ret = new HashCollection(md5Worker.Hash, sha1Worker.Hash, sha256Worker.Hash, sha512Worker.Hash);

            return(ret);
        }
示例#2
0
 public IActionResult Index([FromForm] LoginModel model)
 {
     ViewData["ServerName"] = Program.ServerName;
     ViewData["Title"]      = "登录";
     if (ModelState.IsValid)
     {
         var users = from u in db.Users where u.Username == model.Username select u;
         if (users.Count() != 1)
         {
             ModelState.AddModelError("", "用户名或密码错误!");
             return(View(model));
         }
         var user     = users.First();
         var password = HashWorker.HashPassword(model.Password, user.CreateTime);
         if (password != user.Password)
         {
             ModelState.AddModelError("", "用户名或密码错误!");
             return(View(model));
         }
         HttpContext.Session.Set("User", ByteConverter.ToBytes(user));
         return(RedirectToAction(actionName: "Index", controllerName: "User"));
     }
     else
     {
         return(View(model));
     }
 }
示例#3
0
 public IActionResult Register([FromForm] RegisterModel model)
 {
     ViewData["ServerName"] = Program.ServerName;
     ViewData["Title"]      = "注册";
     if (ModelState.IsValid)
     {
         if (model.VerificationCode == HttpContext.Session.GetString("VerificationCode"))
         {
             var time     = TimeWorker.GetTimeStamp10();
             var password = HashWorker.HashPassword(model.Password, time);
             db.Users.Add(new Users()
             {
                 Username          = model.Username,
                 Email             = model.Email,
                 Password          = password,
                 PreferredLanguage = "zh_CN",
                 CreateIp          = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString(),
                 CreateTime        = time,
                 PermissionLevel   = 0,
                 IsEmailVerified   = 1
             });
             db.SaveChanges();
             return(RedirectToAction(actionName: "Index", controllerName: "User"));
         }
         else
         {
             ModelState.AddModelError(string.Empty, "验证码不正确!");
             return(View("Index", model));
         }
     }
     return(View("Index", model));
 }
示例#4
0
        public async Task <IActionResult> Registration(RegistrationModel model)
        {
            if (ModelState.IsValid)
            {
                ulong phoneULong;
                var   succParse = ulong.TryParse(model.Phone, out phoneULong);
                if (!succParse)
                {
                    return(Problem(statusCode: 400, title: "Pnone incorrect"));
                }
                if (await context.Clients.AnyAsync(c => c.Phone == phoneULong))
                {
                    return(Problem(statusCode: 400, title: "Phone is already in use"));
                }


                var client = new Client()
                {
                    FullName     = model.FullName,
                    Phone        = phoneULong,
                    HashPassword = HashWorker.GetHashString(model.Password)
                };

                await context.Clients.AddAsync(client);

                await context.SaveChangesAsync();

                return(Ok());
            }
            return(BadRequest(ModelState));
        }
        public static string GenerateHash(this Stream stream, HashTypes hashType)
        {
            var worker = new HashWorker(hashType);

            worker.GenerateHash(stream);

            return(BitConverter.ToString(worker.Hash).Replace("-", "").ToLower());
        }
示例#6
0
        public void Basic_TestSha256HashMustSucceed()
        {
            const string randomText         = "SomeRandomText";
            const string expectedRandomHash = "f69804e5a135035020b5c1fdec659fafc6947350a462dca9731e4f14db2e9120";

            var hashValue = HashWorker.GenerateSha256(randomText);

            Assert.AreEqual(expectedRandomHash, hashValue, "Generated hash value did not match as expected");
        }
        public UserEntityBuilder Jane()
        {
            Name     = "Jane";
            Surname  = "Doe";
            Username = "******";
            Password = "******";

            PasswordHash = HashWorker.GenerateSha256(Password);

            return(this);
        }
        public UserEntityBuilder John()
        {
            Name     = "John";
            Surname  = "Doe";
            Username = "******";
            Password = "******";

            PasswordHash = HashWorker.GenerateSha256(Password);

            return(this);
        }
示例#9
0
        public bool Login(string username, string password)
        {
            var storedPasswordhash = _userAdapter.GetPasswordHash(username);

            if (string.IsNullOrWhiteSpace(storedPasswordhash))
            {
                return(false);
            }

            var generateProvidedPasswordHash = HashWorker.GenerateSha256(password);

            return(string.Equals(storedPasswordhash, generateProvidedPasswordHash));
        }
示例#10
0
        public void creatAdmin(string connectionString, string login, string password)
        {
            HashWorkerInterface <HashConfig> hashWorker = new HashWorker();
            HashConfig hc = new HashConfig();

            hc.numberOfHashing = 100000;
            hc.sultLength      = 20;
            hashWorker.setConfig(hc);
            SecurityUserInterface user = new SecurityUser(login, password);

            user.setAdmin(true);
            string sult = hashWorker.getSult(user);

            dataBaseController.configAndExecute(connectionString,
                                                queryConfigurator.addAdmin(user.getLogin(),
                                                                           hashWorker.getHash(user.getPassword(), sult), sult));
        }
示例#11
0
        public async Task <IActionResult> Auth(AuthModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await context.Clients.FirstOrDefaultAsync(c => c.Phone == model.Phone);

                if (user == null)
                {
                    ModelState.AddModelError("Phone", "This phone not found");
                    return(BadRequest(new ValidationProblemDetails(ModelState)));
                }
                if (user.HashPassword != HashWorker.GetHashString(model.Password))
                {
                    ModelState.AddModelError("Auth", "Login or password incorrect");
                    return(BadRequest(new ValidationProblemDetails(ModelState)));
                }
                return(Ok());
            }
            return(BadRequest(ModelState));
        }
示例#12
0
        public JsonResult Signout([FromBody] PostSignoutRequest request)
        {
            log.Info($"[ID: {HttpContext.Connection.Id}]Got logout request from {HttpContext.Connection.RemoteIpAddress.MapToIPv4()}:{HttpContext.Connection.RemotePort} with user {request.username}.");

            // Check if user exists.
            var users = from u in db.Users where u.Email == request.username select u;

            if (users.Count() != 1)
            {
                log.Info($"[ID: {HttpContext.Connection.Id}]Request user is not exists.");
                return(new JsonResult(ExceptionWorker.InvalidUsername())
                {
                    StatusCode = (int)HttpStatusCode.Forbidden
                });
            }

            // Cooldown check.
            var user      = users.First();
            var time      = TimeWorker.GetTimeStamp10();
            var cooldowns = from c in db.Cooldown where c.Uid == user.Id select c;

            if (cooldowns.Count() != 1)
            {
                db.Cooldown.Add(new Cooldown()
                {
                    Uid           = user.Id,
                    TryTimes      = 0,
                    LastTryTime   = time,
                    LastLoginTime = user.CreateTime,
                    CooldownLevel = 0,
                    CooldownTime  = time
                });
                db.SaveChanges();
            }

            cooldowns = from c in db.Cooldown where c.Uid == user.Id select c;
            var cooldown = cooldowns.First();

            if (Convert.ToDecimal(cooldown.CooldownTime) > Convert.ToDecimal(time))
            {
                log.Info($"[ID: {HttpContext.Connection.Id}]User {request.username} already in cooldown.");
                return(new JsonResult(ExceptionWorker.TooManyTryTimes())
                {
                    StatusCode = (int)HttpStatusCode.Forbidden
                });
            }
            else
            {
                if (cooldown.TryTimes >= Program.SecurityLoginTryTimes)
                {
                    cooldown.CooldownLevel++;
                    cooldown.CooldownTime = time + cooldown.CooldownLevel * cooldown.CooldownLevel * 5 * 60;
                    db.SaveChanges();
                    log.Info($"[ID: {HttpContext.Connection.Id}]User {request.username} got into cooldown.");
                    return(new JsonResult(ExceptionWorker.TooManyTryTimes())
                    {
                        StatusCode = (int)HttpStatusCode.Forbidden
                    });
                }
                cooldown.LastTryTime = time;
                cooldown.TryTimes++;
                db.SaveChanges();
            }

            // Password check.
            var salt           = user.CreateTime;
            var passwordHashed = HashWorker.HashPassword(request.password, salt);

            if (user.Password != passwordHashed)
            {
                log.Info($"[ID: {HttpContext.Connection.Id}]IP address {HttpContext.Connection.RemoteIpAddress}:{HttpContext.Connection.RemotePort} try to login with user {request.username} but wrong password.");
                return(new JsonResult(ExceptionWorker.InvalidPassword())
                {
                    StatusCode = (int)HttpStatusCode.Forbidden
                });
            }

            // Update cooldown.
            cooldown.LastLoginTime = time;
            cooldown.TryTimes      = 0;
            db.SaveChanges();
            log.Info($"[ID: {HttpContext.Connection.Id}]Cooldown of user {user.Username} has reseted.");

            return(new JsonResult(null)
            {
                StatusCode = (int)HttpStatusCode.NoContent
            });
        }
示例#13
0
        public JsonResult Authenticate([FromBody] PostAuthrnticateRequest request)
        {
            log.Info($"[ID: {HttpContext.Connection.Id}]Got login request from {HttpContext.Connection.RemoteIpAddress.MapToIPv4()}:{HttpContext.Connection.RemotePort} with user {request.username}.");

            // Check if user exists.
            var users = from u in db.Users where u.Email == request.username select u;

            if (users.Count() != 1)
            {
                log.Info($"[ID: {HttpContext.Connection.Id}]Request user is not exists.");
                return(new JsonResult(ExceptionWorker.InvalidUsername())
                {
                    StatusCode = (int)HttpStatusCode.Forbidden
                });
            }

            // Cooldown check.
            var user      = users.First();
            var time      = TimeWorker.GetTimeStamp10();
            var cooldowns = from c in db.Cooldown where c.Uid == user.Id select c;

            if (cooldowns.Count() != 1)
            {
                db.Cooldown.Add(new Cooldown()
                {
                    Uid           = user.Id,
                    TryTimes      = 0,
                    LastTryTime   = time,
                    LastLoginTime = user.CreateTime,
                    CooldownLevel = 0,
                    CooldownTime  = time
                });
                db.SaveChanges();
            }

            cooldowns = from c in db.Cooldown where c.Uid == user.Id select c;
            var cooldown = cooldowns.First();

            if (Convert.ToDecimal(cooldown.CooldownTime) > Convert.ToDecimal(time))
            {
                log.Info($"[ID: {HttpContext.Connection.Id}]User {user.Username} already in cooldown.");
                return(new JsonResult(ExceptionWorker.TooManyTryTimes())
                {
                    StatusCode = (int)HttpStatusCode.Forbidden
                });
            }
            else
            {
                if (cooldown.TryTimes >= Program.SecurityLoginTryTimes)
                {
                    cooldown.CooldownLevel++;
                    cooldown.CooldownTime = time + cooldown.CooldownLevel * cooldown.CooldownLevel * 5 * 60;
                    db.SaveChanges();
                    log.Info($"[ID: {HttpContext.Connection.Id}]User {user.Username} got into cooldown.");
                    return(new JsonResult(ExceptionWorker.TooManyTryTimes())
                    {
                        StatusCode = (int)HttpStatusCode.Forbidden
                    });
                }
                cooldown.LastTryTime = time;
                cooldown.TryTimes++;
                db.SaveChanges();
            }

            // Password check.
            var salt           = user.CreateTime;
            var passwordHashed = HashWorker.HashPassword(request.password, salt);

            if (user.Password != passwordHashed)
            {
                log.Info($"[ID: {HttpContext.Connection.Id}]IP address {HttpContext.Connection.RemoteIpAddress}:{HttpContext.Connection.RemotePort} try to login with user {request.username} but wrong password.");
                return(new JsonResult(ExceptionWorker.InvalidPassword())
                {
                    StatusCode = (int)HttpStatusCode.Forbidden
                });
            }

            // Update cooldown.
            cooldown.LastLoginTime = time;
            cooldown.TryTimes      = 0;
            db.SaveChanges();
            log.Info($"[ID: {HttpContext.Connection.Id}]Cooldown of user {request.username} has reseted.");

            // Hand token out and select profile.
            var accessToken = UuidWorker.GetUuid();
            var clientToken = string.Empty;

            if (request.clientToken != null)
            {
                clientToken = request.clientToken;
            }
            else
            {
                clientToken = UuidWorker.GetUuid();
            }

            Tokens token = new Tokens()
            {
                AccessToken = accessToken,
                ClientToken = clientToken,
                CreateTime  = time,
                Status      = 2
            };

            PostAuthrnticateResponse response = new PostAuthrnticateResponse();
            var profiles = from p in db.Profiles where p.Uid == user.Id select p;

            List <Profile> availableProfiles = new List <Profile>();

            foreach (var p in profiles)
            {
                var playerProfile = new Profile();
                playerProfile.id   = p.Uuid;
                playerProfile.name = p.Name;

                if (profiles.Count() > 1)
                {
                    if (p.IsSelected == 1)
                    {
                        response.selectedProfile = playerProfile;
                        token.BindProfileId      = p.Id;
                        log.Info($"[ID: {HttpContext.Connection.Id}]User {request.username} has logged and binded profile {playerProfile.name}.");
                    }
                }
                else if (profiles.Count() == 1)
                {
                    response.selectedProfile = playerProfile;
                    token.BindProfileId      = p.Id;
                    p.IsSelected             = 1;
                    log.Info($"[ID: {HttpContext.Connection.Id}]User {request.username} has logged and binded profile {playerProfile.name}.");
                }
                else
                {
                    log.Info($"[ID: {HttpContext.Connection.Id}]User {request.username} has logged but not bind any profile.");
                }

                availableProfiles.Add(playerProfile);
            }


            var tokens = from t in db.Tokens where t.BindProfileId == token.BindProfileId select t;

            foreach (var t in tokens)
            {
                t.Status = 1;
            }
            db.Tokens.Add(token);
            db.SaveChanges();

            // Build response
            response.accessToken = accessToken;
            response.clientToken = clientToken;

            var availableProfilesFinal = availableProfiles.ToArray();

            response.availableProfiles = availableProfilesFinal;

            if (request.requestUser)
            {
                var properties = new Properties()
                {
                    name  = "preferredLanguage",
                    value = user.PreferredLanguage
                };
                response.user = new User()
                {
                    id         = user.Username,
                    properties = new Properties[] { properties }
                };
            }
            return(new JsonResult(response));
        }