// 使用者認證 Authentication public static UserAccount GetAccount(string email, string password) { // 檢查登入者身分 string jsonResult = AccountProxy.GetUserAccount(email, Sha256Helper.Gethash(password)); UserAccount account = null; var jobjAcct = JObject.Parse(jsonResult); try { // 若無效身分則送出登入異常 switch (jobjAcct["ACCOUNT_TYPE"].ToString()) { case "KKdayAccount": account = jobjAcct["ACCOUNT"].ToObject <KKdayAccount>(); break; case "B2dAccount": account = jobjAcct["ACCOUNT"].ToObject <B2dAccount>(); break; default: throw new Exception("Invalid User Login"); } } catch { throw new Exception("Invalid User Login"); }; return(account); }
// 註冊新分銷商 public void Register(RegisterModel reg) { try { if (reg.PASSWORD != null) { reg.PASSWORD = Sha256Helper.Gethash(reg.PASSWORD); reg.USER_UUID = Guid.NewGuid().ToString(); string[] time = reg.TIMEZONE.Split(new char[2] { ',', ':' }); reg.TIMEZONE = time[1]; string[] country = reg.COUNTRY_CODE.Split(new char[1] { ',' }); reg.COUNTRY_CODE = country[0]; reg.TEL_CODE = country[1]; RegisterDAL.InsCompany(reg); } } catch (Exception ex) { throw ex; } }
public ActionResult <string> GenerateDigest([FromBody] string request, SigningAlgoritm algoritm = SigningAlgoritm.SHA256WITHRSA) { _logger.LogDebug($"Calling POST /generateDigest{algoritm} endpoint "); if (request == null) { return(BadRequest()); } try { request = DecodeBase64(request); } catch (Exception ex) { _logger.LogError($"Error decoding request data", ex); return(BadRequest("Error decoding request data, check base64 encoding")); } if (algoritm == SigningAlgoritm.SHA256WITHRSA) { return($"SHA-256={Sha256Helper.GenerateHash(request)}"); } else if (algoritm == SigningAlgoritm.SHA512WITHRSA) { return($"SHA-512={Sha512Helper.GenerateHash(request)}"); } else { return(BadRequest($"Unsupported digest algoritm {algoritm}")); } }
// [共用]新增帳號資訊 public void InsertAccount(B2dAccount acct, string crt_user) { if (acct.PASSWORD != null) { acct.PASSWORD = Sha256Helper.Gethash(acct.PASSWORD); acct.UUID = Guid.NewGuid().ToString(); AccountDAL.InsertAccount(acct, crt_user); } }
public async Task <IActionResult> SubmitUser([FromBody] UserViewModel viewModel) { User user = viewModel.GetDbModel(); user.PasswordHash = Sha256Helper.GetHash(viewModel.Password); cateringDbContext.Add(user); await cateringDbContext.SaveChangesAsync(); return(Ok()); }
// [共用]新增API帳號資訊 public void InsertAccount(B2dAccount acct, string crt_user) { B2dAccount acc = acct as B2dAccount; if (acc.PASSWORD != null) { acc.PASSWORD = Sha256Helper.Gethash(acc.PASSWORD); acc.UUID = Guid.NewGuid().ToString(); ApiAccountDAL.InsertApiAccount_Api(acc, crt_user); } }
public async Task <IActionResult> ChangeUserPassword([FromRoute] int userId, [FromBody] UserPasswordModel model) { User user = await cateringDbContext.Users.FirstOrDefaultAsync(x => x.UserId == userId); string utfPassword = Base64.Base64Decode(model.Password); user.PasswordHash = Sha256Helper.GetHash(utfPassword); cateringDbContext.Update(user); await cateringDbContext.SaveChangesAsync(); return(Ok()); }
// 使用者認證 Authentication public UserAccount GetAccount(string email, string password) { // 檢查登入者身分 UserAccount account = AccountAuthDAL.UserAuth(email, Sha256Helper.Gethash(password)); // 若無效身分則送出登入異常 if (!(account is KKdayAccount) && !(account is B2dAccount)) { throw new Exception("Invalid User Login"); } return(account); }
public static Account Login(string userName, string password) { string hashedPassword = Sha256Helper.GetHashSha256(password); Account acc = AuthenticateDAL.Login(userName, hashedPassword); if (acc != null) { AccountDAL.AddToLoginLog(acc); } return(acc); }
public ActionResult Assertion(int userID, int achievementID) { string userEmail, achievementImageURL; DateTime achievementDate; using (UnitOfWork work = new UnitOfWork()) { // Verify user actually has achievement if (!work.AchievementRepository.DoesUserHaveAchievement(userID, achievementID)) { return(new HttpStatusCodeResult(HttpStatusCode.NotFound)); } // If so, get data and generate assertion userEmail = work.UserRepository.GetUser(userID).email; achievement_template achievementTemplate = work.AchievementRepository.GetTemplateById(achievementID); achievementImageURL = JppUriInfo.GetAbsoluteUri(Request, achievementTemplate.icon); achievement_instance achievementInstance = work.AchievementRepository.GetUserAchievementInstance(userID, achievementID); achievementDate = achievementInstance.achieved_date; } string salt = "CoeA8DQf"; // As we are exposing the salt anyway, using a constant isn't an issue, and it saves us from having to store every randomly-generated salt in the db string hashedEmail; hashedEmail = Sha256Helper.HashStringWithSalt(userEmail, salt); var badgeAssertion = new { uid = GenerateUniqueId(userID, achievementID), recipient = new { identity = "sha256$" + hashedEmail, type = "email", hashed = true, salt = salt }, image = achievementImageURL, badge = JppUriInfo.GetCurrentDomain(Request) + Url.RouteUrl("OpenBadgeDescriptionRoute", new { Action = "BadgeDescription", achievementID = achievementID }), verify = new { type = "hosted", url = JppUriInfo.GetCurrentDomain(Request) + Url.RouteUrl("OpenBadgeRoute", new { Action = "Assertion", userID = userID, achievementID = achievementID }), }, issuedOn = achievementDate.ToString("s", System.Globalization.CultureInfo.InvariantCulture), evidence = JppUriInfo.GetCurrentDomain(Request) + Url.RouteUrl("AchievementsPlayersRoute", new { id = achievementID, playerID = userID }), }; return(Json(badgeAssertion, JsonRequestBehavior.AllowGet)); }
public void Basic() { //// https://passwordsgenerator.net/sha256-hash-generator/ var h3 = Sha256Helper.GenerateHash(" "); Assert.AreEqual("36A9E7F1C95B82FFB99743E0C5C4CE95D83C9A430AAC59F84EF3CBFAB6145068", h3); var h4 = Sha256Helper.GenerateHash("sdfgsdfgs"); Assert.AreEqual("D6C84C6D32D245DDA9CE2E9E3C776767DC877B4C2BDEAEC5CAB3E595D573740A", h4); // https://crypto.stackexchange.com/questions/64442/is-it-possible-to-convert-the-output-of-sha256-hash-to-binary-or-decimal-value var h5 = Sha256Helper.GenerateHash("hello world!"); Assert.AreEqual("60668F3A418FF2F78E6C53BC77910B7945ECD29D4B3D9D3934B89B0B5E84F797", h5); }
internal static Account SaveAccount(Account acc) { using (CoreModel coreDAL = new CoreModel()) { if (acc.ID > 0) { Account account = coreDAL.Account.Include("Club").Include("AccountAccess").Include("Account_Information") .Where(a => a.ID == acc.ID).FirstOrDefault(); account.AccountAccess.ToList().ForEach(a => a.Accessright.Accessright_Right.ToList()); if (account != null) { account.FirstName = acc.FirstName; account.LastName = acc.LastName; account.UserName = acc.UserName; account.Image = acc.Image; account.Gender = acc.Gender; account.Account_Information.ToList().ForEach(a => coreDAL.Entry(a).State = System.Data.Entity.EntityState.Deleted); acc.Account_Information.ToList().ForEach(a => account.Account_Information.Add(a)); account.AccountAccess.ToList().ForEach(a => coreDAL.Entry(a).State = System.Data.Entity.EntityState.Deleted); acc.AccountAccess.ToList().ForEach(a => account.AccountAccess.Add(a)); if (!string.IsNullOrEmpty(acc.Password)) { account.Password = Sha256Helper.GetHashSha256(acc.Password); } coreDAL.SaveChanges(); return(account); } else { return(null); } } else { acc.Password = Sha256Helper.GetHashSha256(acc.Password); coreDAL.Account.Add(acc); coreDAL.SaveChanges(); return(acc); } } }
public string TryLoginUser(LoginAPIModel model) { model.Password = Base64.Base64Decode(model.Password); User user = cateringDbContext.Users .Include(x => x.Role) .Where(x => x.Email == model.Email || x.Username == model.Email) .Where(x => x.PasswordHash == Sha256Helper.GetHash(model.Password)) .FirstOrDefault(); if (user == null) { return(null); } JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); byte[] key = Encoding.ASCII.GetBytes(appSettings.Secret); var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, user.UserId.ToString()), new Claim(JwtRegisteredClaimNames.UniqueName, $"{user.FirstName} {user.LastName}"), new Claim(ClaimTypes.Role, user.Role.RoleTitle) }; SigningCredentials signingCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), SigningCredentials = signingCredentials }; SecurityToken token = tokenHandler.CreateToken(tokenDescriptor); return(tokenHandler.WriteToken(token)); }
public void Null() { Sha256Helper.GenerateHash(null); }
public IActionResult SignData([FromBody] SigningRequest request) { _logger.LogDebug($"Calling POST /generateDigest endpoint "); if (request == null) { return(BadRequest()); } _logger.LogDebug($"Calling POST /generateDigest endpoint "); try { request.DataToSign = DecodeBase64(request.DataToSign); } catch (Exception ex) { _logger.LogError($"Error decoding data to sign", ex); return(BadRequest("Error decoding data to sign, check base64 encoding")); } if (request.Algorithm == SigningAlgoritm.SHA256WITHRSA) { var bytes = Encoding.UTF8.GetBytes(request.DataToSign ?? request.Digest.Replace("SHA-256=", "")); var signBytes = Sha256Helper.SignData(request.PrivateKey, bytes); var signature = Convert.ToBase64String(signBytes); var testValid = Sha256Helper.VerifyData(request.Certificate, bytes, signBytes); var response = new SigningResponse() { Algorithm = Enum.GetName(typeof(SigningAlgoritm), request.Algorithm), Headers = "digest tpp-transaction - id tpp - request - id timestamp psu-id", KeyId = request.KeyID, Signature = signature, CertificateAuthority = "CA", IsValid = testValid }; return(Ok(response)); } else if (request.Algorithm == SigningAlgoritm.SHA512WITHRSA) { var bytes = Encoding.UTF8.GetBytes(request.DataToSign ?? request.Digest.Replace("SHA-512=", "")); var signBytes = Sha512Helper.SignData(request.PrivateKey, bytes); var signature = Convert.ToBase64String(signBytes); var testValid = Sha512Helper.VerifyData(request.Certificate, bytes, signBytes); var response = new SigningResponse() { Algorithm = GetEnumDescription(request.Algorithm), Headers = "digest tpp-transaction - id tpp - request - id timestamp psu-id", KeyId = request.KeyID, Signature = signature, CertificateAuthority = "CA", IsValid = testValid }; return(Ok(response)); } else { return(BadRequest($"Unsupported signing algoritm {request.Algorithm}")); } }
public async Task <IActionResult> AuthenAsync(LoginModel loginModel) { Dictionary <string, string> jsonData = new Dictionary <string, string>(); try { //var accountRepo = (AccountRepository)HttpContext.RequestServices.GetService(typeof(AccountRepository)); var encPassword = WebUtility.UrlEncode(Sha256Helper.Gethash(loginModel.Password)); var account = AccountRepository.GetAccount(loginModel.Email, encPassword); //分流-KKdayUser&UserAdmin var IsKKdayUser = account is KKdayAccount ? true : false; var IsUserAdmin = (account is B2dAccount && ((B2dAccount)account).USER_TYPE.Equals("01")) ? true : false; var strChiperAcct = AesCryptHelper.aesEncryptBase64(JsonConvert.SerializeObject(account), Website.Instance.AesCryptKey); var claims = new List <Claim> { new Claim(ClaimTypes.Name, account.NAME), new Claim("Account", account.EMAIL), new Claim("UUID", account.UUID), new Claim("UserType", IsKKdayUser ? "KKDAY" : (IsUserAdmin ? "ADMIN":"USER")), new Claim("Locale", account.LOCALE), new Claim("Currency", IsKKdayUser ? "" : ((B2dAccount)account).CURRENCY), new Claim(ClaimTypes.UserData, strChiperAcct), // 以AES加密JSON格式把使用者資料保存於Cookie }; //var aesUserData = User.Identities.SelectMany(i => i.Claims.Where(c => c.Type == ClaimTypes.UserData).Select(c => c.Value)).FirstOrDefault(); //var UserData = JsonConvert.DeserializeObject<B2dAccount>(AesCryptHelper.aesDecryptBase64(aesUserData, Website.Instance.AesCryptKey)); var userIdentity = new ClaimsIdentity(claims, "login"); ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity); await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties() { ExpiresUtc = DateTime.UtcNow.AddDays(10), // 預設 Cookie 有效時間 IsPersistent = false, AllowRefresh = false }); if (!IsKKdayUser) { HttpContext.Session.SetString("B2D_COMPANY_LOCALE", ((B2dAccount)account).LOCALE); HttpContext.Session.SetString("B2D_COMPANY_CURRENCY", ((B2dAccount)account).CURRENCY); } jsonData.Add("status", "OK"); //Just redirect to our index after logging in. jsonData.Add("url", IsKKdayUser ? Url.Content("~/KKday/") : Url.Content("~/")); } catch (Exception ex) { jsonData.Clear(); jsonData.Add("status", "ERROR"); jsonData.Add("msg", ex.Message); } return(Json(jsonData)); }
public void EmptyString() { var h1 = Sha256Helper.GenerateHash(string.Empty); Assert.AreEqual("E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855", h1.ToUpperInvariant()); }
public async Task <(string data, DateTime updated)> GetData(string url, DownloadOptions options) { string urlHash = Sha256Helper.GenerateHash(url); return(await GetData(url, $"{urlHash}-Data", $"{urlHash}-Updated", options.Expiry, options.CancelToken, options.IgnoreCache).ConfigureAwait(false)); }