public string save_user(string userId, string userName, string userUserName, string userDesc) { string userPass = ""; using (var db = new dbsmsEntities()) { if (db.users.Select(x => x.username).Contains(userUserName)) { return("0"); } if (String.IsNullOrEmpty(userId)) { user data = new user(); data.name = userName; data.username = userUserName; userPass = userUserName + "123"; data.password = MD5.Hash(userPass); data.description = userDesc; data.status = 1; db.users.Add(data); } else { user data = db.users.Find(Convert.ToInt64(userId)); data.name = userName; data.username = userUserName; data.password = MD5.Hash(userPass); data.description = userDesc; } db.SaveChanges(); } return("1"); }
public static void editUser(user u) { using (var context = new STOK_TAKIPEntities()) { //get sql parameters for edituser procedure using (MD5 md5 = MD5.Create()) { //Hashing with MD5 string strHashedPassword = md5.Hash(u.password); var userID = new SqlParameter("@userID", u.id); var userName = new SqlParameter("@username", u.username); var userPassword = new SqlParameter("@password", strHashedPassword); try { //execute edituser stored procedure context.Database.ExecuteSqlCommand("exec editUser @userID , @username , @password", userID, userName, userPassword); MessageBox.Show("The transaction was successful!"); ucLoans.Instance = null; ucProduct.Instance = null; ucRemoveProduct.Instance = null; ucUndoProduct.Instance = null; ucDepartmentChief.Instance = null; } catch { MessageBox.Show("The transaction was failed!"); } } } }
public ActionResult Login(ACCOUNT login, string ReturnUrl = "") { string message = ""; var v = db.ACCOUNTs.Where(a => a.EMAIL == login.EMAIL).FirstOrDefault(); if (v != null) { if (string.Compare(MD5.Hash(login.PASSWORD), v.PASSWORD) == 0) { int timeout = login.RememberMe ? 525600 : 20; var ticket = new FormsAuthenticationTicket(login.EMAIL, login.RememberMe, timeout); string encrypted = FormsAuthentication.Encrypt(ticket); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted); cookie.Expires = DateTime.Now.AddMinutes(timeout); cookie.HttpOnly = true; Response.Cookies.Add(cookie); var name = v.EMAIL.Split('@'); Session.Add("Email", name[0]); return(RedirectToAction("Index", "Home", new { id = HttpUtility.UrlEncode((name[0])) + "/" })); } else { message = "Tài khoản hoặc mật khẩu chưa đúng."; } } else { message = "Tài khoản không tồn tại."; } ViewBag.Message = message; return(View()); }
private void KeyExchange(ref Byte encryptMode) { while (keyExchanging) { Thread.Sleep(1); } if (key != null || encryptMode == 0) { return; } if ((key == null) && keyExchanged) { encryptMode = 0; return; } keyExchanging = true; Hashtable result = POST("phprpc_encrypt=true&phprpc_keylen=" + keylen); if (result.ContainsKey("phprpc_keylen")) { keylen = (UInt32)result["phprpc_keylen"]; } else { keylen = 128; } if (result.ContainsKey("phprpc_encrypt")) { AssocArray encrypt = (AssocArray)Deserialize((Byte[])result["phprpc_encrypt"]); BigInteger x = BigInteger.GenerateRandom((Int32)keylen - 1); x.SetBit(keylen - 2); BigInteger y = BigInteger.Parse(PHPConvert.ToString(encrypt["y"])); BigInteger p = BigInteger.Parse(PHPConvert.ToString(encrypt["p"])); BigInteger g = BigInteger.Parse(PHPConvert.ToString(encrypt["g"])); if (keylen == 128) { this.key = new byte[16]; Byte[] k = y.ModPow(x, p).GetBytes(); for (Int32 i = 1, n = Math.Min(k.Length, 16); i <= n; i++) { this.key[16 - i] = k[n - i]; } } else { key = MD5.Hash(encoding.GetBytes(y.ModPow(x, p).ToString())); } POST("phprpc_encrypt=" + g.ModPow(x, p).ToString()); } else { key = null; keyExchanged = true; encryptMode = 0; } keyExchanging = false; }
public String reset_pass(String userid) { using (var db = new dbsmsEntities()) { user data = db.users.Find(Convert.ToInt64(userid)); data.password = MD5.Hash(data.username + "123"); db.SaveChanges(); } return("reset ke username + 123"); }
public static void PopulateWithLoginInfo(this CallLoginInfo call) { call.username = UserName; call.auth_method = "challenge"; GetChallengeReply reply = MakeCall.GetChallenge(); call.auth_challenge = reply.challenge; call.auth_response = MD5.Hash(reply.challenge + PasswordHash); call.clientversion = ClientVersion; }
/// <summary> /// 实例化CustomBinarySerializationProtocol /// </summary> /// <param name="compress"></param> /// <param name="encrypt"></param> public CustomWireProtocol(bool compress, bool encrypt) { this.compress = compress; this.encrypt = encrypt; if (encrypt) { //获取加密的字符串 var encryptString = BigInteger.GenerateRandom(128).ToString(); keys = MD5.Hash(Encoding.UTF8.GetBytes(encryptString)); } }
public void Hash_MD5() { MD5 md = new MD5(); Assert.AreEqual("d41d8cd98f00b204e9800998ecf8427e", md.Hash("")); //Assert.AreEqual("0cc175b9c0f1b6a831c399e269772661", md.Hash("a")); //Assert.AreEqual("900150983cd24fb0d6963f7d28e17f72", md.Hash("abc")); //Assert.AreEqual("f96b697d7cb7938d525a2f31aaf161d0", md.Hash("message digest")); //Assert.AreEqual("c3fcd3d76192e4007dfb496cca67e13b", md.Hash("abcdefghijklmnopqrstuvwxyz")); //Assert.AreEqual("d174ab98d277d9f5a5611c2c9f419d9f", md.Hash("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")); //Assert.AreEqual("57edf4a22be3c955ac49da2e2107b67a", md.Hash("12345678901234567890123456789012345678901234567890123456789012345678901234567890")); }
public async Task <string> Initialize(string server, string characterId, int level, bool useToken = false) { using (HttpClientHandler handler = new HttpClientHandler { CookieContainer = AcapulcoBot.GetInstance.GetCookies() }) { using (HttpClient client = new HttpClient(handler)) { client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Dalvik/2.1.0 (Linux; U; Android 8.0.0; Samsung Galaxy S8 - 8.0 - API 26 - 1440x2960 Build/OPR6.170623.017)"); client.DefaultRequestHeaders.TryAddWithoutValidation("X-Unity-Version", "5.6.2p4"); Uri url = new Uri(string.Concat(new string[] { $"http://{server}", ".margonem.pl/engine?t=init&initlvl=", $"{level}", $"&mucka={Mucka.GenerateMucka()}", "&mobile=1", useToken ? $"&mobile_token={_characterToken}" : "" })); AcapulcoBot.GetInstance.GetCookies().Add(url, new Cookie("mchar_id", characterId)); string response = await client.GetStringAsync(url); if (level == 1) { Match m = Regex.Match(response, "\"mobile_token\": \"(.*?)\","); if (m.Success) { _characterToken = MD5.Hash(m.Groups[1].Value); } else { MessageBox.Show("Ta postać jest zarejestrowana na innym świecie.", "Acapulco Bot", MessageBoxButtons.OK, MessageBoxIcon.Error); Environment.Exit(0); } } else if (level == 4) { Match m = Regex.Match(response, "\"ev\": (.*?),"); if (m.Success) { _characterEvent = m.Groups[1].Value; } _server = server; _id = characterId; } return(response); } } }
public void SetLoginPassword(string st) { if (st == null) { confirmLogInButton.SetActive(false); return; } hashedPassword = md5.Hash(st); if (username != null) { confirmLogInButton.SetActive(true); } }
public ActionResult Edit([Bind(Include = "EMAIL,ID_CUSTOMER,PASSWORD,CONFIRMPASSWORD,ISEMAILVERIFY,ACTIVATIONCODE,RESETPASSWORDCODE")] ACCOUNT aCCOUNT) { if (ModelState.IsValid) { aCCOUNT.PASSWORD = MD5.Hash(aCCOUNT.PASSWORD); aCCOUNT.CONFIRMPASSWORD = MD5.Hash(aCCOUNT.CONFIRMPASSWORD); db.Entry(aCCOUNT).State = EntityState.Modified; db.SaveChanges(); ViewBag.SuccessMessage = "Sửa thành công."; } else { ViewBag.FailMessage = "Sửa không thành công."; } return(View(aCCOUNT)); }
protected void ButtonGenerateGraphUrl_Click(object sender, EventArgs e) { this.PanelGraphUrl.Visible = true; double xSize = Double.Parse(this.TextWidth.Text.Replace(",", ".")); double ySize = Double.Parse(this.TextHeight.Text.Replace(",", ".")); if (this.DropUnit.SelectedValue == "cm") { xSize /= 2.54; ySize /= 2.54; } xSize *= 300; // dpi ySize *= 300; Geography geo = GeographyTreeDropDown1.SelectedGeography; if (geo == null) { geo = Geography.Root; } string geoVerify = MD5.Hash(geo.GeographyId.ToString() + "Pirate").Replace(" ", ""); string orgHost = ""; if (DropDownListOrg.SelectedValue == Organization.PPSEid.ToString()) { orgHost = "piratpartiet"; } else { orgHost = "ungpirat"; } string url = String.Format("http://data." + orgHost + ".se/Charts/MemberCountHistory.aspx?EndDate={0}&Days={1}&XSize={2}&YSize={3}&Geo={4}&Validate={5}", this.PickEndDate.SelectedDate.Value.ToString("yyyy-MM-dd"), (this.PickEndDate.SelectedDate.Value.Date - this.PickDateTime.SelectedDate.Value.Date).Days, (int)xSize, (int)ySize, geo.GeographyId, geoVerify); this.LinkGraph.NavigateUrl = url; this.LinkGraph.Text = url; this.LabelCountResults.Text = this.GetMemberCount(Organization.FromIdentity(Convert.ToInt32(DropDownListOrg.SelectedValue)), false, Geography.Root, (DateTime)this.PickDateTime.SelectedDate).ToString(); }
/// <summary> /// Generates password hashes for legacy passwords in system (that are no longer generated). /// </summary> /// <param name="person">The person to generate a hash for.</param> /// <param name="password">The password to hash.</param> /// <returns>A list of previously valid password hashes.</returns> private static string[] GenerateLegacyPasswordHashes(Person person, string password) { if (person.PersonalNumber.Length > 0) { return(new[] { SHA1.Hash(password + person.Identity + "Pirate"), MD5.Hash(password + person.PersonalNumber + "Pirate") }); } else { return new[] { SHA1.Hash(password + person.Identity + "Pirate") } }; }
/// <summary> /// Generates password hashes for legacy passwords in system (that are no longer generated). /// </summary> /// <param name="person">The person to generate a hash for.</param> /// <param name="password">The password to hash.</param> /// <returns>A list of previously valid password hashes.</returns> private static string[] GenerateLegacyPasswordHashes(Person person, string password) { // Calling Obsolete Property is valid here since we are generationg legacy hashes. #pragma warning disable 618 if (person.PersonalNumber.Length > 0) { return(new[] { SHA1.Hash(password + person.Identity + "Pirate"), MD5.Hash(password + person.PersonalNumber + "Pirate") }); } return(new[] { SHA1.Hash(password + person.Identity + "Pirate") }); #pragma warning restore 618 }
public ActionResult Login(String username, String password) { using (var db = new dbsmsEntities()) { password = MD5.Hash(password); try { user usr = (from u in db.users where u.username == username && u.password == password select u).First(); Session["user"] = usr.username; return(RedirectToAction("Index", "Home")); } catch (Exception e) { TempData["message"] = "Invalid Username or Password"; } return(RedirectToAction("Index", "Login")); } }
public string change_password(string oldPassword, string newPassword) { using (var db = new dbsmsEntities()) { try { string pass = MD5.Hash(oldPassword); string username = Session["user"].ToString(); user user_ = (from u in db.users where u.password == pass && u.username == username select u).First(); user_.password = MD5.Hash(newPassword); db.SaveChanges(); return("1"); } catch (System.Exception e) { return("0"); } } }
public void ShouldHashFilesAsBase64() { var tempFile = string.Format("{0}{1}.dat", Path.GetTempPath(), Guid.NewGuid()); const string testString = "My test content to hash with special chars 123!|\"£$%&/()=<>{}[]"; File.WriteAllText(tempFile, testString); var result = _sut.Hash(new FileInfo(tempFile)).ToString(BinaryRepresentation.Base64); result.Should().Be.EqualTo("9YCcj/qhIvCff9/89SWwBw=="); // Cleanup if (File.Exists(tempFile)) { File.Delete(tempFile); } }
// Login user check public static void checkUser(user model) { using (var context = new STOK_TAKIPEntities()) { try { using (MD5 md5 = MD5.Create()) { //Hashing with MD5 string strHashedPassword = md5.Hash(model.password); using (var db = new STOK_TAKIPEntities()) { var result = db.users.Select(s => s) .Where(x => x.username == model.username) .Where(x => x.password == strHashedPassword); ucProduct.Instance = null; ucLoans.Instance = null; frm login = new frm(); string[] authors = { result.First().username, result.First().name, result.First().lastName, result.First().id.ToString(), result.First().userTypeID.ToString() }; login.GetUser = authors; login.ShowDialog(); return; } } } catch { MessageBox.Show("Username or password wrong!"); } } }
public static void addUser(user u) { using (var context = new STOK_TAKIPEntities()) { try { using (MD5 md5 = MD5.Create()) { string strHashedPassword = md5.Hash(u.password); context.addUser(u.name, u.lastName, u.username, strHashedPassword, u.userTypeID); ucUsers.Instance = null; ucLoantoUser.Instance = null; ucEditUser.Instance = null; MessageBox.Show("User Created"); } } catch { MessageBox.Show("Something went wrong!"); } } }
public ActionResult ResetPassword(ResetPasswordModel model) { var message = ""; if (ModelState.IsValid) { var account = db.ACCOUNTs.Where(a => a.RESETPASSWORDCODE == model.ResetCode).FirstOrDefault(); if (account != null) { account.PASSWORD = MD5.Hash(model.NewPassword); account.CONFIRMPASSWORD = MD5.Hash(model.ConfirmPassword); account.RESETPASSWORDCODE = ""; db.Configuration.ValidateOnSaveEnabled = false; db.SaveChanges(); message = "Mật khẩu mới đã được cập nhật thành công"; } } else { message = "Something invalid"; } ViewBag.Message = message; return(View(model)); }
public static ActionResult CacheView(this Controller me, string viewName, object model, int duration = 900) { if (model != null) { me.ViewData.Model = model; } var viewEngineResult = FindView(me, viewName, null); var cacheKey = MD5.Hash(((RazorView)viewEngineResult.View).ViewPath); CacheView cacheView; if (MustRefresh(me.Request.Headers["Cache-Control"], out var prolonged)) { cacheView = RenderAndCacheForcibly(me, viewEngineResult.View, cacheKey, duration + prolonged); } else { cacheView = RenderAndCache(me, viewEngineResult.View, cacheKey, duration); if (NotModified(me.ViewBag.CacheViewIdentity, cacheKey, cacheView.Checksum)) { return(new HttpStatusCodeResult(HttpStatusCode.NotModified).SetCacheHeader( me.Response, $"{cacheKey}-{cacheView.Checksum}")); } } viewEngineResult.ViewEngine.ReleaseView(me.ControllerContext, viewEngineResult.View); return(new ContentResult { Content = cacheView.Output, ContentType = "text/html" }.SetCacheHeader( me.Response, $"{cacheKey}-{cacheView.Checksum}")); }
private void NextKeyExchange(Object state) { RequestState requestState = state as RequestState; Hashtable result = GetResponseBody(requestState.response, 0); #if SILVERLIGHT if (result.ContainsKey("phprpc_url")) { String phprpc_url = (String)result["phprpc_url"]; url = new Uri(phprpc_url); if (url.Query == "") { url = new Uri(phprpc_url + "?phprpc_id=" + clientID); } else { url = new Uri(phprpc_url + "&phprpc_id=" + clientID); } } #endif if (result.ContainsKey("phprpc_keylen")) { keylen = (UInt32)result["phprpc_keylen"]; } else { keylen = 128; } if (result.ContainsKey("phprpc_encrypt")) { AssocArray encrypt = (AssocArray)Deserialize((Byte[])result["phprpc_encrypt"]); BigInteger x = BigInteger.GenerateRandom((Int32)keylen - 1); x.SetBit(keylen - 2); BigInteger y = BigInteger.Parse(PHPConvert.ToString(encrypt["y"])); BigInteger p = BigInteger.Parse(PHPConvert.ToString(encrypt["p"])); BigInteger g = BigInteger.Parse(PHPConvert.ToString(encrypt["g"])); if (keylen == 128) { this.key = new byte[16]; Byte[] k = y.ModPow(x, p).GetBytes(); for (Int32 i = 1, n = Math.Min(k.Length, 16); i <= n; i++) { this.key[16 - i] = k[n - i]; } } else { key = MD5.Hash(encoding.GetBytes(y.ModPow(x, p).ToString())); } requestState = new RequestState(); requestState.bufferWrite = encoding.GetBytes("phprpc_encrypt=" + g.ModPow(x, p).ToString()); requestState.asyncCallback = new SendOrPostCallback(EndKeyExchange); POST(requestState); } else { key = null; requestState.encryptMode = 0; keyExchanged = true; EndKeyExchange(null); } }
public static string ToMD5(this string str) { return(MD5.Hash(str)); }
protected void Button1_Click(object sender, EventArgs e) { string res; upload up = new upload(); res = up.Up3(File1, "/lwhPersonal/uploads/excel/", "student"); if (Convert.ToInt32(res) == 3) { string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + up.s3 + ";Extended Properties=Excel 8.0"; //链接Excel OleDbConnection cnnxls = new OleDbConnection(strConn); //读取Excel里面有 表Sheet1 OleDbDataAdapter oda = new OleDbDataAdapter("select * from [Sheet1$]", cnnxls); DataSet ds = new DataSet(); //将Excel里面有表内容装载到内存表中! oda.Fill(ds); DataTable dt = ds.Tables[0]; try { for (int i = 0; i < dt.Rows.Count; i++) { string sql1 = "SELECT classId FROM class WHERE name = N'" + dt.Rows[i]["class"].ToString().Trim() + "'"; string sql2 = "SELECT COUNT(*) FROM studentlist WHERE name = N'" + dt.Rows[i]["userName"] + "'"; string sql3 = "SELECT COUNT(*) FROM studentlist WHERE studyNum = N'" + dt.Rows[i]["studyNum"] + "'"; string sql4 = "SELECT COUNT(*) FROM studentlist WHERE sclass = " + Convert.ToInt32(DB.FindString(sql1)) + " AND classNum = " + Convert.ToInt32(dt.Rows[i]["classNum"]) + " "; if (Convert.ToInt32(DB.FindString(sql2)) == 0 && Convert.ToInt32(DB.FindString(sql3)) == 0 && Convert.ToInt32(DB.FindString(sql4)) == 0) { string sql = "INSERT INTO studentlist(name,nickname,password,sclass,studyNum,classNum)VALUES(N'" + dt.Rows[i]["userName"] + "',N'" + dt.Rows[i]["name"] + "',N'" + MD5.Hash(dt.Rows[i]["password"].ToString()) + "'," + Convert.ToInt32(DB.FindString(sql1)) + ",N'" + dt.Rows[i]["studyNum"] + "','" + Convert.ToInt32(dt.Rows[i]["classNum"]) + "')"; DB.execnonsql(sql); } } Response.Write("<script>alert('导入成功!');</script>"); } catch { Response.Write("<script>alert('导入出错,请检查excel表!');</script>"); } } else { Response.Write("<script>alert('" + up.Resup3[Convert.ToInt32(res)] + "');</script>"); //this.Label1.Visible = true; //this.Label1.Text = up.Resup3[Convert.ToInt32(res)]; } }
private void KeyExchange() { if (session == null) { throw new Exception("Session seems not start, Please start Session first."); } Hashtable sessionObject; InitKeylen(); if (encrypt) { DHParams dhParams = new DHParams(keylen); keylen = dhParams.GetL(); BigInteger p = dhParams.GetP(); BigInteger g = dhParams.GetG(); BigInteger x = dhParams.GetX(); BigInteger y = g.ModPow(x, p); sessionObject = new Hashtable(); sessionObject["x"] = x; sessionObject["p"] = p; sessionObject["keylen"] = keylen; session.Contents[cid] = sessionObject; Hashtable dhp = dhParams.GetDHParams(); dhp["y"] = y.ToString(); buffer.Append("phprpc_encrypt=\""); buffer.Append(EncodeString(Serialize(dhp))); buffer.Append("\";\r\n"); if (keylen != 128) { buffer.Append("phprpc_keylen=\""); buffer.Append(keylen); buffer.Append("\";\r\n"); } SendURL(); } else { sessionObject = (Hashtable)session.Contents[cid]; lock (sessionObject.SyncRoot) { BigInteger x = (BigInteger)sessionObject["x"]; BigInteger p = (BigInteger)sessionObject["p"]; if (keylen == 128) { key = new byte[16]; Byte[] k = y.ModPow(x, p).GetBytes(); for (Int32 i = 1, n = Math.Min(k.Length, 16); i <= n; i++) { this.key[16 - i] = k[n - i]; } } else { key = MD5.Hash(Encoding.ASCII.GetBytes(y.ModPow(x, p).ToString())); } sessionObject["key"] = key; sessionObject.Remove("x"); sessionObject.Remove("p"); session.Contents[cid] = sessionObject; } } SendCallback(); }
public CacheView(string output) { this.Output = output; this.Checksum = MD5.Hash(output); }
private void ljPassword_Leave(object sender, EventArgs e) { LoginInfo.PasswordHash = MD5.Hash(ljPassword.Text); Registry.Write("Password", LoginInfo.PasswordHash); }
protected void Page_Load(object sender, EventArgs e) { // Get organization metadata. OrganizationMetadata metadata = OrganizationMetadata.FromUrl(Request.Url.Host); Organization org = Organization.FromIdentity(metadata.OrganizationId); // Set the title. Chart.Title = "Member count history - " + org.NameShort; // Change the shading mode Chart.ShadingEffectMode = ShadingEffectMode.Three; // Set the x axis label Chart.ChartArea.XAxis.Label.Text = ""; Chart.XAxis.TimeScaleLabels.Mode = TimeScaleLabelMode.Smart; string dayCountString = Request.QueryString["Days"]; if (dayCountString != null) { int dayCount = Int32.Parse(dayCountString); if (dayCount < 32) { Chart.XAxis.TimeScaleLabels.DayFormatString = "dd"; Chart.XAxis.TimeScaleLabels.MonthFormatString = "dd"; Chart.XAxis.TimeInterval = TimeInterval.Day; } else if (dayCount < 180) { Chart.XAxis.TimeInterval = TimeInterval.Month; } } string geoID = Request.QueryString["Geo"]; string geoValidate = Request.QueryString["Validate"]; Geography geo = null; int geoIntId = -1; if (geoID != null || geoValidate != null) { //want to filter by geography. if (geoID == null || geoValidate == null) { //bad request Response.Write("Sorry, that request was not correctly formed"); Response.End(); } if (geoValidate != MD5.Hash(geoID + "Pirate").Replace(" ", "")) { //bad request Response.Write("Sorry, that request was not correctly formed."); Response.End(); } if (!int.TryParse(geoID, out geoIntId)) { //bad request Response.Write("Sorry, that request was not correctly formed.."); Response.End(); } geo = Geography.FromIdentity(geoIntId); Chart.Title += " - " + geo.Name; } // Set the y axis label //Chart.ChartArea.YAxis.Label.Text = "Ung Pirat SE - medlemsgraf"; // Set the directory where the images will be stored. Chart.TempDirectory = "temp"; // Set the chart size. Chart.Width = 600; Chart.Height = 350; // If different sizes were given as parameters, adjust. string xSize = Request.QueryString["XSize"]; string ySize = Request.QueryString["YSize"]; string format = Request.QueryString["ImageFormat"]; if (!String.IsNullOrEmpty(xSize)) { Chart.Width = Int32.Parse(xSize); } if (!String.IsNullOrEmpty(ySize)) { Chart.Height = Int32.Parse(ySize); } if (!String.IsNullOrEmpty(format)) { Chart.ImageFormat = (ImageFormat)Enum.Parse(typeof(ImageFormat), format); } Chart.SeriesCollection.Add(GetGrowthData(metadata, geo)); Chart.LegendBox.Position = LegendBoxPosition.None; Chart.Debug = false; Chart.Mentor = false; }
private void Login_Click(object sender, RoutedEventArgs e) { LoginProgressBar.Visibility = Visibility.Visible; var loginCred = new LoginCredentials { Username = Username.Text, Password = Password.Password }; //Missing information. This is done to save bandwidth for the user. // if (string.IsNullOrWhiteSpace(loginCred.Username) || string.IsNullOrWhiteSpace(loginCred.PasswordHash)) { UserInterfaceCore.HolderPage.ShowNotification(UserInterfaceCore.ShortNameToString("NoCred")); LoginProgressBar.Visibility = Visibility.Hidden; return; } var t = new Thread(async() => { var accountInfo = AccountManager.GetAccountInfo(loginCred); // Failed login information if (!string.IsNullOrWhiteSpace(accountInfo.Error)) { switch (accountInfo.Error) { case "InvalidCred": case "UserBanned": case "EmailNotVerified": await Dispatcher.BeginInvoke(DispatcherPriority.Render, (Action)(() => { UserInterfaceCore.HolderPage.ShowNotification(UserInterfaceCore.ShortNameToString(accountInfo.Error)); LoginProgressBar.Visibility = Visibility.Hidden; Password.Clear(); })); break; default: await Dispatcher.BeginInvoke(DispatcherPriority.Render, (Action)(() => { UserInterfaceCore.HolderPage.ShowNotification(UserInterfaceCore.ShortNameToString("LoginErrorGeneric")); LoginProgressBar.Visibility = Visibility.Hidden; Password.Clear(); })); break; } return; } if (!string.IsNullOrWhiteSpace(accountInfo.TwoFactor)) { LoginProgressBar.Visibility = Visibility.Hidden; switch (accountInfo.Error) { //TODO: Implement a way to input a code for 2FA //TODO: Add an option to exclude 2FA for certain known devices of IP ADDRESSES case "CheckEmail": case "CheckText": await Dispatcher.BeginInvoke(DispatcherPriority.Render, (Action)(() => { UserInterfaceCore.HolderPage.ShowNotification(UserInterfaceCore.ShortNameToString(accountInfo.Error)); LoginProgressBar.Visibility = Visibility.Hidden; })); break; default: await Dispatcher.BeginInvoke(DispatcherPriority.Render, (Action)(() => { UserInterfaceCore.HolderPage.ShowNotification(UserInterfaceCore.ShortNameToString("LoginErrorGeneric")); LoginProgressBar.Visibility = Visibility.Hidden; })); break; } return; } //This is the OpenId config used to login. I use a custom //Implementation which may not fully represent OpenId but //It gets the job done var openId = RiotAuth.GetOpenIdConfig(); //The SHA1 Hash of the password is used as the password //To get the accounts from the servers. The MD5 hash of that //Password is the AES key. This may need to change to a different //Hashing algorithm, and maybe the encryption should include //A part form the IcyWindAuth server which is used to decrypt var aesKey = MD5.Hash(Password.Password); StaticVars.AccountInfo = accountInfo; StaticVars.LoginCred = loginCred; StaticVars.Password = aesKey; //This is done to stop people who are not devs or donators from accessing IcyWind in Beta // ReSharper disable once ConditionIsAlwaysTrueOrFalse if (!accountInfo.IsDev && !accountInfo.IsPaid && false) { await Dispatcher.BeginInvoke(DispatcherPriority.Render, (Action)(() => { UserInterfaceCore.HolderPage.ShowNotification(UserInterfaceCore.ShortNameToString("FeaturedDonator")); })); return; } if (!string.IsNullOrWhiteSpace(accountInfo.Accounts)) { foreach (var account in JsonConvert.DeserializeObject <string[]>(accountInfo.Accounts)) { var copyAccount = account; var mm = copyAccount.Length % 4; if (mm > 0) { copyAccount += new string('=', 4 - mm); } var data = Convert.FromBase64String(copyAccount); var accountAsJson = Encoding.UTF8.GetString(data); var decodedString = JsonConvert.DeserializeObject <IcyWindRiotAccountCrypted>(accountAsJson); if (StaticVars.LoginCred.AccountData == null) { StaticVars.LoginCred.AccountData = new List <IcyWindRiotAccountCrypted>(); } StaticVars.LoginCred.AccountData.Add(decodedString); var accountDecrypted = AES.DecryptBase64(aesKey, decodedString.CryptString); var accountDetail = JsonConvert.DeserializeObject <IcyWindRiotAccountInfo>(accountDecrypted); await RiotAuth.Login(this, Dispatcher, accountDetail.Username, accountDetail.Password, accountDetail.Region, openId, true, null); } } else { StaticVars.LoginCred.AccountData = new List <IcyWindRiotAccountCrypted>(); } await Dispatcher.BeginInvoke(DispatcherPriority.Render, (Action)(() => { UserInterfaceCore.ChangeView(typeof(AccountSelectorPage)); //Fade out the audio var timer = new System.Timers.Timer { Interval = 50 }; timer.Elapsed += (obj, evt) => { Dispatcher.BeginInvoke(DispatcherPriority.Render, (Action)(() => { player.Volume -= 0.01; if (!(player.Volume <= 0)) { return; } player.Stop(); timer.Stop(); Video.Stop(); })); }; timer.Start(); LoginProgressBar.Visibility = Visibility.Hidden; })); }); t.Start(); }
public string getHash() { MD5 hasher = new MD5(); return hasher.Hash(theArray); }
private string MD5(string !hashValue) { byte[] vals = Encoding.ASCII.GetBytes(hashValue); byte[] result = (!)fMD5.Hash(vals); return(ToHexString(result)); }