protected void but_user_Click(object sender, EventArgs e) { string name = UserName.Value.Trim(); string ut = User_Type.SelectedValue; string pwd = new Encrypt().Get_MD5_Method32(PassWord.Value); string pwd1 = PassWord1.Value; string pwd2 = PassWord2.Value; if (Convert.ToInt32(ut) > userType || userType == 0|| name.Equals(Request.Cookies["user"]["UserName"])) { if (!name.Equals(string.Empty) && pwd1.Equals(pwd2)) { _PassWord.Visible = true; B_User b = new B_User(); DataTable dt = b.getUserByID(id); if (pwd.Equals(dt.Rows[0]["Password"])) { _oldPwd.Visible = true; if (action.Equals("edit")) { R_User r = new R_User(); r.ID = id; r.Password = new Encrypt().Get_MD5_Method32(pwd1); if (b.editUser(r)) { Response.Redirect("User.aspx"); } else { Response.Write("<script>alert('修改失败')</script>"); } } } else { _oldPwd.Visible = false; } } else if (!pwd1.Equals(pwd2)) { _PassWord.Visible = false; } } else { Response.Write("<script>alert('用户权限不足,不能修改!')</script>"); } }
public Encrypt Encode(EncryptType type, string value) { try { string finalKey = cryptoKey.PadRight(KeyLength, FillCharacter); var result = new Encrypt(); result.Type = EncryptType.OK; RijndaelManaged crypto = null; MemoryStream mStream = null; ICryptoTransform encryptor = null; CryptoStream cryptoStream = null; byte[] plainBytes = System.Text.Encoding.UTF8.GetBytes(value); try { crypto = new RijndaelManaged(); crypto.KeySize = 128; crypto.Padding = PaddingMode.PKCS7; // HERE IS THE "ISSUE" // The default mode on .NET 4 is CBC, wich seems not to be the case on MonoTouch. crypto.Mode = CipherMode.CBC; encryptor = crypto.CreateEncryptor(Encoding.UTF8.GetBytes(finalKey), Encoding.UTF8.GetBytes(finalKey)); mStream = new MemoryStream(); cryptoStream = new CryptoStream(mStream, encryptor, CryptoStreamMode.Write); cryptoStream.Write(plainBytes, 0, plainBytes.Length); } finally { if (crypto != null) crypto.Clear(); cryptoStream.Close(); } result.Value = mStream.ToArray(); return result; } catch (Exception) { return null; } }
public string Decode(Encrypt obj) { string finalKey = cryptoKey.PadRight(KeyLength, FillCharacter); RijndaelManaged crypto = null; MemoryStream mStream = null; ICryptoTransform decryptor = null; CryptoStream cryptoStream = null; try { byte[] cipheredData = obj.Value; crypto = new RijndaelManaged(); crypto.KeySize = 128; crypto.Padding = PaddingMode.PKCS7; decryptor = crypto.CreateDecryptor(Encoding.UTF8.GetBytes(finalKey), Encoding.UTF8.GetBytes(finalKey)); mStream = new System.IO.MemoryStream(cipheredData); cryptoStream = new CryptoStream(mStream, decryptor, CryptoStreamMode.Read); StreamReader creader = new StreamReader(cryptoStream, Encoding.UTF8); String data = creader.ReadToEnd(); return data; } catch (Exception ex) { return null; } finally { if (crypto != null) { crypto.Clear(); } if (cryptoStream != null) { cryptoStream.Close(); } } }
protected void but_login_Click(object sender, EventArgs e) { if (Request.Cookies["CheckCode"] != null) { if (vdcode.Value.ToUpper().Equals(Request.Cookies["CheckCode"].Value.ToUpper())) { string user = userid.Text.Trim(); string password = new Encrypt().Get_MD5_Method32(pwd.Text.Trim()); B_User b = new B_User(); DataTable dt = b.selUser(user); if (dt.Rows.Count == 1) { DataRow dr = dt.Rows[0]; if (dr["Password"].Equals(password)) { int id = Convert.ToInt32(dr["ID"].ToString()); if (b.updatalogin(id)) { string usertype = dr["User_Type"].ToString(); Response.Cookies["user"]["ID"] = id.ToString(); Response.Cookies["user"]["UserName"] = System.Web.HttpContext.Current.Server.UrlEncode(user); Response.Cookies["user"]["UserType"] = usertype; Response.Redirect("Default.aspx"); } } else { Response.Write("<script>alert('密码不正确!')</script>"); } } else { Response.Write("<script>alert('用户名不正确!')</script>"); } } else { Response.Write("<script>alert('验证码输入不正确!')</script>"); } } }
public virtual void Encrypt ( Encrypt Options ) { char UsageFlag = '-'; { #pragma warning disable 219 Encrypt Dummy = new Encrypt (); #pragma warning restore 219 Console.Write ("{0}encrypt ", UsageFlag); Console.WriteLine (); Console.WriteLine (" Encrypt a data file to a label"); } Console.WriteLine ("Not Yet Implemented"); }
private static void Usage () { Console.WriteLine ("brief"); Console.WriteLine (""); { #pragma warning disable 219 Reset Dummy = new Reset (); #pragma warning restore 219 Console.Write ("{0}reset ", UsageFlag); Console.WriteLine (); Console.WriteLine (" Delete all test profiles"); } { #pragma warning disable 219 Device Dummy = new Device (); #pragma warning restore 219 Console.Write ("{0}device ", UsageFlag); Console.Write ("[{0}] ", Dummy.DeviceID.Usage (null, "id", UsageFlag)); Console.Write ("[{0}] ", Dummy.DeviceDescription.Usage (null, "dd", UsageFlag)); Console.Write ("[{0}] ", Dummy.Default.Usage ("default", "value", UsageFlag)); Console.WriteLine (); Console.WriteLine (" Create new device profile"); } { #pragma warning disable 219 Personal Dummy = new Personal (); #pragma warning restore 219 Console.Write ("{0}personal ", UsageFlag); Console.Write ("[{0}] ", Dummy.Portal.Usage (null, "portal", UsageFlag)); Console.Write ("[{0}] ", Dummy.Description.Usage (null, "pd", UsageFlag)); Console.Write ("[{0}] ", Dummy.Verbose.Usage ("verbose", "value", UsageFlag)); Console.Write ("[{0}] ", Dummy.Report.Usage ("report", "value", UsageFlag)); Console.Write ("[{0}] ", Dummy.DeviceNew.Usage ("new", "value", UsageFlag)); Console.Write ("[{0}] ", Dummy.DeviceUDF.Usage ("dudf", "value", UsageFlag)); Console.Write ("[{0}] ", Dummy.DeviceID.Usage ("did", "value", UsageFlag)); Console.Write ("[{0}] ", Dummy.DeviceDescription.Usage ("dd", "value", UsageFlag)); Console.WriteLine (); Console.WriteLine (" Create new personal profile"); } { #pragma warning disable 219 Label Dummy = new Label (); #pragma warning restore 219 Console.Write ("{0}label ", UsageFlag); Console.Write ("[{0}] ", Dummy.Portal.Usage ("portal", "value", UsageFlag)); Console.Write ("[{0}] ", Dummy.UDF.Usage ("udf", "value", UsageFlag)); Console.WriteLine (); Console.WriteLine (" Create new security label"); } { #pragma warning disable 219 Add Dummy = new Add (); #pragma warning restore 219 Console.Write ("{0}add ", UsageFlag); Console.WriteLine (); Console.WriteLine (" Add user to a label"); } { #pragma warning disable 219 Remove Dummy = new Remove (); #pragma warning restore 219 Console.Write ("{0}remove ", UsageFlag); Console.WriteLine (); Console.WriteLine (" Remove user from a label"); } { #pragma warning disable 219 Rekey Dummy = new Rekey (); #pragma warning restore 219 Console.Write ("{0}rekey ", UsageFlag); Console.WriteLine (); Console.WriteLine (" Create a new label key and recryption keys"); } { #pragma warning disable 219 Encrypt Dummy = new Encrypt (); #pragma warning restore 219 Console.Write ("{0}encrypt ", UsageFlag); Console.WriteLine (); Console.WriteLine (" Encrypt a data file to a label"); } { #pragma warning disable 219 Decrypt Dummy = new Decrypt (); #pragma warning restore 219 Console.Write ("{0}decrypt ", UsageFlag); Console.WriteLine (); Console.WriteLine (" Decrypt a data file"); } } // Usage
public OnlineUser Login(UserLoginDto dto) { //当前时间 var localTime = DateTime.Now.ToLocalTime(); var ip = IpHelper.GetUserIp(); var request = HttpContext.Current.Request; //创建客户端信息获取实体 var clientHelper = new ClientHelper(request); User user; using (var dao = new DataBaseContext()) { user = dao.Set <User>().Single(u => u.AccountName == dto.AccountName); if (user == null) { throw new Exception($"登录失败,用户不存在!(帐号:{dto.AccountName})"); } //密码不匹配 if (!user.Password.Equals(Encrypt.Md5(Encrypt.Md5(dto.Password)))) { throw new Exception("登录失败,密码错误!"); } //已注销用户不能登录 if (user.UserState == UserState.Cancelled) { throw new Exception("登录失败,您已经没有权限登录本系统!"); } //判断当前账号是否被启用 if (user.UserState == UserState.Disable) { throw new Exception("登录失败,当前账号未被启用,请联系管理人员激活!"); } //检查用户权限 //检查用户是否允许多点登录 //创建在线用户 var onlineUser = new OnlineUser(); //当前用户的Id编号 onlineUser.UserId = user.Id; onlineUser.AccountName = user.AccountName; onlineUser.Password = user.Password; onlineUser.Name = user.Name; onlineUser.LoginTime = localTime; onlineUser.LoginIp = ip; //生成密钥 onlineUser.UserKey = RandomHelper.GetRndNum(32, true); //Md5(密钥+登陆帐号+密码+IP+密钥.Substring(6,8)) onlineUser.Md5 = GenerateMd5(onlineUser); HttpContext.Current.Session[OnlineUsersTable.Md5] = onlineUser.Md5; onlineUser.UpdateTime = localTime; onlineUser.Sex = user.Sex; //onlineUser.Branch_Id = user.Branch_Id; //onlineUser.Branch_Code = user.Branch_Code; //onlineUser.Branch_Name = user.Branch_Name; //onlineUser.Position_Id = user.Position_Id; //onlineUser.Position_Name = user.Position_Name; //onlineUser.CurrentPage = ""; //onlineUser.CurrentPageTitle = ""; //SessionId onlineUser.SessionId = HttpContext.Current.Session.SessionID; onlineUser.UserAgent = StringHelper.FilterSql(HttpContext.Current.Request.Headers["User-Agent"] + ""); onlineUser.OpeartingSystem = clientHelper.GetSystem(); onlineUser.TerminalType = clientHelper.IsMobileDevice(onlineUser.UserAgent) ? 1 : 0; onlineUser.BrowserName = clientHelper.GetBrowserName(); onlineUser.BrowserVersion = clientHelper.GetBrowserVersion(); #region 记录当前用户UserId //定义HashTable表里Key的名称UserId string userHashKey = ""; //判断当前用户帐户是否支持同一帐号在不同地方登陆功能,取得用户在HashTable表里Key的名称 //不支持则 if (user.IsMultiUser) { userHashKey = user.Id + ""; } //支持则 else { userHashKey = user.Id + "_" + onlineUser.SessionId; } //记录用户的HashTable Key onlineUser.UserHashKey = userHashKey; HttpContext.Current.Session[OnlineUsersTable.UserHashKey] = userHashKey; #endregion #region 将在线用户信息存入全局变量中 //运行在线数据加载函数,如果缓存不存在,则尝试加载数据库中的在线表记录到缓存中 //——主要用于IIS缓存被应用程序池或其他原因回收后,对在线数据进行重新加载,而不会使所有用户都被迫退出系统 var onlineUsersList = GetList(); //判断缓存中["OnlineUsers"]是否存在,不存在则直接将在线实体添加到缓存中 if (onlineUsersList == null || onlineUsersList.Count == 0) { //清除在线表里与当前用户同名的记录 Delete(x => x.AccountName == onlineUser.AccountName); //将在线实体保存到数据库的在线表中 Save(onlineUser, null, true, false); } //存在则将它取出HashTable并进行处理 else { //将HashTable里存储的前一登陆帐户移除 //获取在线缓存实体 var onlineModel = GetOnlineUser(userHashKey); if (onlineModel != null) { ////添加用户下线记录 //LoginLogBll.GetInstence().Save(userHashKey, "用户【{0}】的账号已经在另一处登录,本次登陆下线!在线时间【{1}】"); //清除在线表里与当前用户同名的记录 Delete(x => x.UserId == onlineUser.UserId); } //将在线实体保存到数据库的在线表中 Save(onlineUser, null, true, false); } #endregion //检查在线列表数据,将不在线人员删除 CheckOnline(); //不在线用户全部下线 //保存当前在线用户 user.LoginIp = ip; user.LoginCount = ++user.LoginCount; user.LoginTime = localTime; var entity = dao.Entry(user); entity.State = EntityState.Modified; dao.SaveChanges(); } return(null); }
private IGrid <TBL_BALANCE_TRANSFER_LOGS> CreateExportableGridINExcel() { var db = new DBContext(); var transactionlist = (from x in db.TBL_BALANCE_TRANSFER_LOGS join y in db.TBL_MASTER_MEMBER on x.FROM_MEMBER equals y.MEM_ID where x.STATUS == "Pending" select new { Touser = "******", TransId = x.TransactionID, FromUser = y.UName, REQUEST_DATE = x.REQUEST_DATE, AMOUNT = x.AMOUNT, BANK_ACCOUNT = x.BANK_ACCOUNT, TRANSACTION_DETAILS = x.TRANSACTION_DETAILS, SLN = x.SLN }).AsEnumerable().Select(z => new TBL_BALANCE_TRANSFER_LOGS { ToUser = z.Touser, TransactionID = z.TransId, FromUser = z.FromUser, AMOUNT = z.AMOUNT, REQUEST_DATE = z.REQUEST_DATE, BANK_ACCOUNT = z.BANK_ACCOUNT, TRANSACTION_DETAILS = z.TRANSACTION_DETAILS, SLN = z.SLN }).ToList(); IGrid <TBL_BALANCE_TRANSFER_LOGS> grid = new Grid <TBL_BALANCE_TRANSFER_LOGS>(transactionlist); grid.ViewContext = new ViewContext { HttpContext = HttpContext }; grid.Query = Request.QueryString; grid.Columns.Add(model => model.TransactionID).Titled("Trans Id"); grid.Columns.Add(model => model.ToUser).Titled("To User"); grid.Columns.Add(model => model.FromUser).Titled("From Member"); grid.Columns.Add(model => model.REQUEST_DATE).Titled("Req Date").Formatted("{0:d}").MultiFilterable(true); grid.Columns.Add(model => model.AMOUNT).Titled("Amount"); grid.Columns.Add(model => model.BANK_ACCOUNT).Titled("Bank Acnt"); grid.Columns.Add(model => model.TRANSACTION_DETAILS).Titled("Pay Method"); grid.Columns.Add(model => model.SLN).Titled("").Encoded(false).Filterable(false).Sortable(false) .RenderedAs(model => "<a href='" + @Url.Action("RequisitionDetails", "Requisition", new { transId = Encrypt.EncryptMe(model.SLN.ToString()) }) + "' class='btn btn-primary btn-xs'>Edit</a>"); grid.Columns.Add(model => model.SLN).Titled("").Encoded(false).Filterable(false).Sortable(false) .RenderedAs(model => "<button class='btn btn-primary btn-xs' data-toggle='modal' data-target='.transd' id='transactionvalueid' data-id=" + model.SLN + " onclick='getvalue(" + model.SLN + ");'>Approve</button>"); grid.Columns.Add(model => model.SLN).Titled("").Encoded(false).Filterable(false).Sortable(false) .RenderedAs(model => "<a href='javascript:void(0)' class='btn btn-denger btn-xs' onclick='DeactivateTransactionlist(" + model.SLN + ");return 0;'>Deactivate</a>"); grid.Pager = new GridPager <TBL_BALANCE_TRANSFER_LOGS>(grid); grid.Processors.Add(grid.Pager); grid.Pager.RowsPerPage = 6; foreach (IGridColumn column in grid.Columns) { column.Filter.IsEnabled = true; column.Sort.IsEnabled = true; } return(grid); }
public Password() { m_ClearPassword = Encrypt.CreateRandomStrongPassword(8); m_Salt = Encrypt.CreateRandomSalt(); m_SaltedPassword = Encrypt.ComputeSaltedHash(m_Salt, m_ClearPassword); }
public sys_user LoginValidate(string uname, string pwd) { pwd = Encrypt.DesEncrypt(pwd); return(Sqldb.Queryable <sys_user>().Where(s => s.account_name == uname && s.pass_word == pwd).First()); }
public async Task <IActionResult> UploadMedicalRecord([FromBody] UploadMedicalRecordInput input) { Patient patient = await dbContext.Patients.FirstOrDefaultAsync(p => p.Id == input.PatientId); if (patient == null) { return(BadRequest(Json(new { Error = "不存在该患者" }))); } InitialDiagnosis initialDiagnosis = await dbContext.InitialDiagnoses.FirstOrDefaultAsync(i => i.PatientId == patient.Id); if (initialDiagnosis == null) { return(BadRequest(Json(new { Error = "该患者未填写初步诊断" }))); } PastMedicalHistory pastMedicalHistory = await dbContext.PastMedicalHistories.FirstOrDefaultAsync(p => p.PatientId == patient.Id); if (pastMedicalHistory == null) { return(BadRequest(Json(new { Error = "该患者未填写既往史" }))); } Symptom symptom = await dbContext.Symptoms.FirstOrDefaultAsync(s => s.PatientId == patient.Id); if (symptom == null) { return(BadRequest(Json(new { Error = "该患者未填写症状体征信息" }))); } List <FoodInfo> foodInfos = await dbContext.FoodInfos.Where(f => f.PatientId == patient.Id).ToListAsync(); XmlHelper xmlHelper = new XmlHelper(); string requestXml = ""; if (input.OperationType == 3) { requestXml = xmlHelper.ConvertToXml(input.OperationType, apiOptions, patient); } else { requestXml = xmlHelper.ConvertToXml(input.OperationType, apiOptions, patient, initialDiagnosis, pastMedicalHistory, symptom, foodInfos); } ReportServiceClient reportService = new ReportServiceClient(); string responseString = await reportService.WEBRequestAsync(Encrypt.Base64Encode(requestXml)); string responseXmlString = Encrypt.Base64Decode(responseString); XmlReader xmlReader = XmlReader.Create(new StringReader(responseXmlString)); XDocument xdoc = XDocument.Load(xmlReader); UploadMedicalRecordOutput output = new UploadMedicalRecordOutput { Code = Convert.ToInt32(xdoc.Element("接口").Element("操作状态").Value), Msg = xdoc.Element("接口").Element("状态描述").Value }; if (input.OperationType == 1 && output.Code == 1) { patient.Status = "已上传"; } if (input.OperationType == 3 && output.Code == 1) { patient.Status = "正常"; } dbContext.Patients.Update(patient); dbContext.SaveChanges(); return(new ObjectResult(output)); }
public ActionResult Register(RegisterInputModel inputModel) { if (string.IsNullOrEmpty(inputModel.Phone.Trim())) { return(Json(new JsonSimpleResponse() { ErrorCode = -5, ErrorMsg = "请输入手机号" })); } if (string.IsNullOrEmpty(inputModel.SmsCode.Trim())) { return(Json(new JsonSimpleResponse() { ErrorCode = -6, ErrorMsg = "请输入手机验证码" })); } if (string.IsNullOrEmpty(inputModel.Name.Trim())) { return(Json(new JsonSimpleResponse() { ErrorCode = -7, ErrorMsg = "请输入姓名" })); } if (inputModel.Grade <= 0) { return(Json(new JsonSimpleResponse() { ErrorCode = -8, ErrorMsg = "请选择年级" })); } if (SmsCookie.GetSmsCode == null || !SmsCookie.GetSmsCode.Check(inputModel.Phone, inputModel.SmsCode)) { return(new JsonResult() { Data = AjaxResponse.Fail(SmsErrorEnum.PhoneCodeFault) }); } StudentInfoBll studentInfoBll = new StudentInfoBll(); var isExist = studentInfoBll.IsExistPhone(inputModel.Phone); if (isExist) { return(Json(new JsonSimpleResponse() { ErrorCode = -9, ErrorMsg = "手机号已存在" })); } inputModel.Password = Encrypt.GetMD5Pwd(inputModel.Password); DtoStudentRegister register = inputModel.ConvertTo <DtoStudentRegister>(); int studentId = studentInfoBll.Register(register); if (studentId > 0) { DtoSumStudentTip sumStudent = studentInfoBll.GetSumStudentTip(studentId); LoginInfo info = sumStudent.ConvertTo <LoginInfo>(); LoginStudent.Info = JsonConvert.SerializeObject(info); return(Json(new JsonSimpleResponse() { State = true, ErrorMsg = "注册成功", ErrorCode = 1 })); } return(Json(new JsonSimpleResponse() { State = false, ErrorMsg = "注册失败", ErrorCode = -1 })); }
private void connectModel() { logsConfigurationModel = new LogsConfiguration(); encrypt = new Encrypt(); }
public override void OnException(ExceptionContext filterContext) { var responseResult = new ResponseResult <object>(); var canPersistence = false; //获取当前登录者的用户信息 var currentLoginUser = Global.Global.GetAdminLoginInfo(); //获取当前用户请求数据(不可直接记录本内容到数据库或本地磁盘) var requestBodyRawString = filterContext.HttpContext.Request.GetRequestBodyString(); //加密请求数据(推荐) var requestBodyEncryptString = Encrypt.MD5Encrypt(requestBodyRawString); //构建日志实体 var logEntry = new T_SYS_LOG { Level = "ERROR", CreateTime = DateTime.Now, RequestParameter = requestBodyEncryptString, Url = filterContext.HttpContext.Request.Path, }; if (currentLoginUser != null) { logEntry.UserId = currentLoginUser.User.Id; logEntry.UserName = currentLoginUser.User.RealName ?? currentLoginUser.User.UserName; } try { filterContext.ExceptionHandled = true; filterContext.HttpContext.Response.StatusCode = 200; filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; responseResult.IsSuccess = false; responseResult.State.Id = (int)ResponseStatusCode.ApplicationError; responseResult.Message = ResponseStatusCode.ApplicationError.GetDescription(); filterContext.HttpContext.Response.Clear(); throw filterContext.Exception; } catch (ArgumentException) { //参数错误 responseResult.State.Id = (int)ResponseStatusCode.ExpectError; responseResult.State.Description = ResponseStatusCode.ExpectError.GetDescription(); responseResult.Message = ResponseStatusCode.InvalidArgument.GetDescription(); } catch (UnauthorizedAccessException) { //未被授权的访问 responseResult.State.Id = (int)ResponseStatusCode.ExpectError; responseResult.State.Description = ResponseStatusCode.ExpectError.GetDescription(); responseResult.Message = ResponseStatusCode.AccessDenied.GetDescription(); } catch (EntityException ex) { //数据库异常 responseResult.State.Id = (int)ResponseStatusCode.DbServerError; responseResult.State.Description = ResponseStatusCode.DbServerError.GetDescription(); responseResult.Message = ResponseStatusCode.DbServerError.GetDescription(); logEntry.Message = ExceptionHelper.Build(ex); logEntry.StackTrace = ex.StackTrace; canPersistence = true;//标记该错误需要被记下来 } catch (CustomException ex) { //预期异常 responseResult.State.Id = (int)ResponseStatusCode.ExpectError; responseResult.State.Description = ResponseStatusCode.ExpectError.GetDescription(); responseResult.Message = ex.Message; logEntry.Message = ExceptionHelper.Build(ex); logEntry.StackTrace = ex.StackTrace; } catch (Exception ex) { if (ex is SqlException && ex.Message.Contains("FK_")) { responseResult.Message = "该数据条目下有关联数据,已终止操作!"; responseResult.State.Id = (int)ResponseStatusCode.ExpectError; responseResult.State.Description = ResponseStatusCode.ExpectError.GetDescription(); } else { //系统错误 responseResult.State.Id = (int)ResponseStatusCode.ApplicationError; responseResult.State.Description = ResponseStatusCode.ApplicationError.GetDescription(); responseResult.Message = ResponseStatusCode.ApplicationError.GetDescription(); logEntry.Message = ExceptionHelper.Build(ex); logEntry.StackTrace = ex.StackTrace; canPersistence = true;//标记该错误需要被记下来 } } finally { filterContext.HttpContext.Response.ContentType = "application/json;charset=utf-8"; filterContext.HttpContext.Response.Write(JsonHelper.ToJsJson(responseResult)); } filterContext.HttpContext.Response.End(); #region 日志记录 var logDateString = DateTime.Now.ToString("\r\n---------MM/dd/yyyy HH:mm:ss,fff---------\r\n"); var currentRequestUrl = "/" + filterContext.HttpContext.Request.HttpMethod + " " + filterContext.HttpContext.Request.Url + "\r\n"; var logOnDiskContent = logDateString + currentRequestUrl + requestBodyEncryptString + "\r\nError:" + logEntry.Message + "\r\n"; if (filterContext.Exception.InnerException != null) { logEntry.Message += "\r\n内部异常:" + filterContext.Exception.InnerException.Message + "\r\n"; } //如果需要持久化,将日志分别记录到本地和数据库中(日志核心数据已加密) if (canPersistence) { //在网站本地生成日志文件 IOHelper.WriteLogToFile(logOnDiskContent, filterContext.HttpContext.Server.MapPath("~/App_Data/Log")); //记录日志到数据库 logRepository.Insert(logEntry); } #endregion }
public ActionResult ChangePassword(ChangePasswordModel model) { string currentPerson = GetCurrentAccount().UID; ViewBag.PersonNamea = currentPerson; if (string.IsNullOrWhiteSpace(currentPerson)) { ModelState.AddModelError("Error_PwdModify", "对不起,请重新登陆"); return(View()); } if (ModelState.IsValid) { if (null != (SMUSERTBService.ValidateUser(currentPerson, Encrypt.DecodeText(model.OldPassword)))) { if (SMUSERTBService.ChangePassword(currentPerson, Encrypt.DecodeText(model.OldPassword), Encrypt.DecodeText(model.NewPassword))) { ModelState.AddModelError("Error_PwdModify", "修改密码成功"); return(View()); } } } ModelState.AddModelError("Error_PwdModify", "修改密码不成功,请核实数据"); return(View()); }
public List <PDWPModel.Agenda> GetCalendarData(int month, int year, int province, string host, string controller) { var agenda = db.Iris_Get_Agendas(month, year, province).OrderBy(x => x.Date).ToList(); var list = new List <PDWPModel.Agenda>(); foreach (var item in agenda) { var obj = new PDWPModel.Agenda { AgendaId = Encrypt.Encryption(item.AgendaId + "", "urbanunit"), Title = item.Title, AgendaNumber = item.AgendaNumber, Date = item.Date, FinancialYearId = item.FinancialYearId, FinancialYearName = item.FinancialYearName, AgendaAttachment = item.AgendaAttachment, AgendaAttachmentPath = $"{host}/api/{controller}/AgendaAttachment/{Encrypt.Encryption(item.AgendaId + "", "urbanunit")}", //item.AgendaAttachmentPath?.Replace("~", "http://iris.urbanunit.gov.pk/"), MeetingStatus = item.MeetingStatus, Status = item.Status, AttachmentStatus = item.AttachmentStatus }; var wps = db.Iris_Get_Agenda_WorkingPapers(item.AgendaId); var events = wps.GroupBy(x => x.WorkingPaperId).Select(x => new Events { AdpNo = x.FirstOrDefault()?.AdpSerial, Title = x.FirstOrDefault()?.WorkingPaperTitle, Sector = x.FirstOrDefault()?.SectorName, EstimatedCost = x.FirstOrDefault()?.EstimatedCost + "", AdpAllocation = x.FirstOrDefault()?.AdpAllocation + "", MeetingStatus = x.FirstOrDefault()?.MeetingStatus, Detail = new EventDetail { Districts = x.FirstOrDefault()?.DistName, ExecutingAgency = x.FirstOrDefault()?.ExecAgencyName, RevisedCost = x.FirstOrDefault()?.AdpCost + "", SchemeCode = "", SponsoringAgency = x.FirstOrDefault()?.SponAgencyName, SubSector = x.FirstOrDefault()?.SubsectorName, Pc1 = x.Where(y => y.AttachmentTypeId == 1).OrderByDescending(y => y.AttachmentDate).Select(pc => new Attachments { Attachment = pc.Attachment, Name = pc.AttachmentName, Path = $"{host}/api/{controller}/WorkingPaperAttachment/{Encrypt.Encryption(pc.AttachmentId + "", "urbanunit")}", //pc.AttachmentPath?.Replace("~", "http://iris.urbanunit.gov.pk/"), Date = pc.AttachmentDate, AttachmentStatus = item.AttachmentStatus }).ToArray(), Pc2 = x.Where(y => y.AttachmentTypeId == 2).OrderByDescending(y => y.AttachmentDate).Select(pc => new Attachments { Attachment = pc.Attachment, Name = pc.AttachmentName, Path = $"{host}/api/{controller}/WorkingPaperAttachment/{Encrypt.Encryption(pc.AttachmentId + "", "urbanunit")}", //pc.AttachmentPath?.Replace("~", "http://iris.urbanunit.gov.pk/"), Date = pc.AttachmentDate, AttachmentStatus = item.AttachmentStatus }).ToArray(), Pc3 = x.Where(y => y.AttachmentTypeId == 3).OrderByDescending(y => y.AttachmentDate).Select(pc => new Attachments { Attachment = pc.Attachment, Name = pc.AttachmentName, Path = $"{host}/api/{controller}/WorkingPaperAttachment/{Encrypt.Encryption(pc.AttachmentId + "", "urbanunit")}", //pc.AttachmentPath?.Replace("~", "http://iris.urbanunit.gov.pk/"), Date = pc.AttachmentDate, AttachmentStatus = item.AttachmentStatus }).ToArray(), Pc4 = x.Where(y => y.AttachmentTypeId == 4).OrderByDescending(y => y.AttachmentDate).Select(pc => new Attachments { Attachment = pc.Attachment, Name = pc.AttachmentName, Path = $"{host}/api/{controller}/WorkingPaperAttachment/{Encrypt.Encryption(pc.AttachmentId + "", "urbanunit")}", //pc.AttachmentPath?.Replace("~", "http://iris.urbanunit.gov.pk/"), Date = pc.AttachmentDate, AttachmentStatus = item.AttachmentStatus }).ToArray(), Pc5 = x.Where(y => y.AttachmentTypeId == 5).OrderByDescending(y => y.AttachmentDate).Select(pc => new Attachments { Attachment = pc.Attachment, Name = pc.AttachmentName, Path = $"{host}/api/{controller}/WorkingPaperAttachment/{Encrypt.Encryption(pc.AttachmentId + "", "urbanunit")}", //pc.AttachmentPath?.Replace("~", "http://iris.urbanunit.gov.pk/"), Date = pc.AttachmentDate, AttachmentStatus = item.AttachmentStatus }).ToArray(), MeetingsPrePDWP = x.Where(y => y.AttachmentTypeId == 15 || y.AttachmentTypeId == 9 || y.AttachmentTypeId == 10).OrderByDescending(y => y.AttachmentDate).Select(pc => new MeetingsPrePDWP { Presentation = pc.AttachmentTypeId == 10 ? $"{host}/api/PDWP/WorkingPaperAttachment/{Encrypt.Encryption(pc.AttachmentId + "", "urbanunit")}" : "", // pc.AttachmentPath?.Replace("~", "http://iris.urbanunit.gov.pk/") Mom = pc.AttachmentTypeId == 9 ? $"{host}/api/PDWP/WorkingPaperAttachment/{Encrypt.Encryption(pc.AttachmentId + "", "urbanunit")}" : "", WorkingPaper = pc.AttachmentTypeId == 15 ? $"{host}/api/PDWP/WorkingPaperAttachment/{Encrypt.Encryption(pc.AttachmentId + "", "urbanunit")}" : "", Pre_PDWP = pc.AttachmentName, Date = pc.AttachmentDate, FileName = pc.Attachment, AttachmentStatus = item.AttachmentStatus }).ToArray(), MeetingsPDWP = x.Where(y => y.AttachmentTypeId == 6 || y.AttachmentTypeId == 7 || y.AttachmentTypeId == 8 || y.AttachmentTypeId == 17).OrderByDescending(y => y.AttachmentDate).Select(pc => new MeetingsPDWP { Presentation = pc.AttachmentTypeId == 7 ? $"{host}/api/PDWP/WorkingPaperAttachment/{Encrypt.Encryption(pc.AttachmentId + "", "urbanunit")}" : "", Mom = pc.AttachmentTypeId == 8 ? $"{host}/api/PDWP/WorkingPaperAttachment/{Encrypt.Encryption(pc.AttachmentId + "", "urbanunit")}" : "", WorkingPaper = pc.AttachmentTypeId == 6 ? $"{host}/api/PDWP/WorkingPaperAttachment/{Encrypt.Encryption(pc.AttachmentId + "", "urbanunit")}" : "", Agenda = pc.AttachmentTypeId == 17 ? $"{host}/api/PDWP/WorkingPaperAttachment/{Encrypt.Encryption(pc.AttachmentId + "", "urbanunit")}" : "", Pdwp = pc.AttachmentName, Date = pc.AttachmentDate, FileName = pc.Attachment, AttachmentStatus = item.AttachmentStatus }).ToArray(), MeetingsCDWP = x.Where(y => y.AttachmentTypeId == 12 || y.AttachmentTypeId == 13 || y.AttachmentTypeId == 14).OrderByDescending(y => y.AttachmentDate).Select(pc => new MeetingsCDWP { WorkingPaper = pc.AttachmentTypeId == 12 ? $"{host}/api/PDWP/WorkingPaperAttachment/{Encrypt.Encryption(pc.AttachmentId + "", "urbanunit")}" : "", Presentation = pc.AttachmentTypeId == 13 ? $"{host}/api/PDWP/WorkingPaperAttachment/{Encrypt.Encryption(pc.AttachmentId + "", "urbanunit")}" : "", Mom = pc.AttachmentTypeId == 14 ? $"{host}/api/PDWP/WorkingPaperAttachment/{Encrypt.Encryption(pc.AttachmentId + "", "urbanunit")}" : "", Cdwp = pc.AttachmentName, Date = pc.AttachmentDate, FileName = pc.Attachment, AttachmentStatus = item.AttachmentStatus }).ToArray(), LiveMonitoringDash = x.Where(y => !string.IsNullOrEmpty(y.LiveMonitoringDash)).OrderByDescending(y => y.AttachmentDate).Select(pc => new LiveMonitoringDash { Name = pc.AttachmentName, File = $"{host}/api/{controller}/WorkingPaperAttachment/{Encrypt.Encryption(pc.AttachmentId + "", "urbanunit")}" }).ToArray(), MonitoringReports = x.Where(y => y.AttachmentTypeId == 11).OrderByDescending(y => y.AttachmentDate).Select(pc => new MonitoringReports { Name = pc.AttachmentName, Date = pc.AttachmentDate, Attachment = pc.Attachment, Path = $"{host}/api/{controller}/WorkingPaperAttachment/{Encrypt.Encryption(pc.AttachmentId + "", "urbanunit")}", AttachmentStatus = item.AttachmentStatus }).ToArray(), } }).ToArray(); obj.Events = events; list.Add(obj); } return(list); }
protected void Page_Load(object sender, EventArgs e) { try { string charset = "utf-8"; string notifyService = "notify_verify"; string sellerEmail = this.so["OnlinePay_Alipay_UserName"].ToString(""); string notifyID = base.Request.QueryString["notify_id"]; int notifyType = 2; Shove.Alipay.Alipay alipay = new Shove.Alipay.Alipay(); string str5 = alipay.Get_Http(notifyService, notifyID, sellerEmail, charset, notifyType, 0x1d4c0); string[] strArray2 = Alipay.Gateway.Utility.BubbleSort(base.Request.QueryString.AllKeys); StringBuilder builder = new StringBuilder(); for (int i = 0; i < strArray2.Length; i++) { if ((!string.IsNullOrEmpty(strArray2[i]) && (base.Request.QueryString[strArray2[i]] != "")) && ((strArray2[i] != "sign") && (strArray2[i] != "sign_type"))) { if (i == (strArray2.Length - 1)) { builder.Append(strArray2[i] + "=" + base.Request.QueryString[strArray2[i]]); } else { builder.Append(strArray2[i] + "=" + base.Request.QueryString[strArray2[i]] + "&"); } } } string str6 = alipay.GetMD5(builder.ToString(), sellerEmail, charset); string str7 = base.Request.QueryString["sign"]; string str8 = base.Request.QueryString["trade_status"]; string str9 = base.Request.QueryString["trade_no"]; string str10 = base.Request.QueryString["out_trade_no"]; string text1 = base.Request.QueryString["payment_type"]; string d = base.Request.QueryString["subject"]; string str = Encrypt.UnEncryptString(PF.GetCallCert(), d); double num3 = double.Parse(base.Request.QueryString["total_fee"].ToString()); string str13 = base.Request.QueryString["seller_email"]; if (str13 != this.so["OnlinePay_Alipay_UserName"].ToString("")) { new Log("System").Write("在线支付:收款帐号不匹配!"); PF.GoError(1, "支付用户信息验证失败", base.GetType().BaseType.FullName); } else if (((str6 == str7) && (str5 == "true")) && (str8 == "TRADE_FINISHED")) { Users users; if (base._User == null) { users = new Users(base._Site.ID)[base._Site.ID, _Convert.StrToLong(str, -1L)]; } else { users = new Users(base._Site.ID)[base._Site.ID, base._User.ID]; } if (users == null) { new Log("System").Write("在线支付:异常用户数据!"); base.Response.Write("<script language='javascript'>window.top.location.href='" + Shove._Web.Utility.GetUrl() + "/Home/Room/MyIcaile.aspx?SubPage=OnlinePay/Fail.aspx'</script>"); } else { if (base._User == null) { base._User = new Users(base._Site.ID)[base._Site.ID, users.ID]; } if (this.WriteUserAccount(base._User, str10.ToString(), num3.ToString(), "系统交易号:" + str10.ToString() + ",支付宝交易号:" + str9.ToString())) { base.Response.Write("<script language='javascript'>window.top.location.href='http://" + Shove._Web.Utility.GetUrlWithoutHttp() + "/Home/Room/MyIcaile.aspx?SubPage=OnlinePay/OK.aspx'</script>"); } else { new Log("System").Write("在线支付:写入返回数据出错!"); base.Response.Write("<script language='javascript'>window.top.location.href='http://" + Shove._Web.Utility.GetUrlWithoutHttp() + "/Home/Room/MyIcaile.aspx?SubPage=OnlinePay/Fail.aspx'</script>"); } } } else { new Log("System").Write("在线支付:系统交易号:" + str10 + " 支付宝交易号:" + str9 + " 校验出错!responseTxt系统要求参数为true/false,实际返回:" + str5.ToString() + " trade_status系统要求返回TRADE_FINISHED,实际返回: " + str8.ToString() + " 生成校验码:" + str6.ToString() + "返回校验码:" + str7.ToString()); base.Response.Write("<script language='javascript'>window.top.location.href='http://" + Shove._Web.Utility.GetUrlWithoutHttp() + "/Home/Room/MyIcaile.aspx?SubPage=OnlinePay/Fail.aspx'</script>"); } } catch (Exception exception) { new Log("System").Write("在线支付:" + exception.Message + " -- 接收数据异常!"); base.Response.Write("<script language='javascript'>window.top.location.href='http://" + Shove._Web.Utility.GetUrlWithoutHttp() + "/Home/Room/MyIcaile.aspx?SubPage=OnlinePay/Fail.aspx'</script>"); } }
public string Decode(Encrypt obj) { if (obj.Type == EncryptType.OK) { try { Cipher c = Cipher.GetInstance("AES"); //c.Init(Javax.Crypto.CipherMode.DecryptMode, obj.Key as IKey); c.Init(Javax.Crypto.CipherMode.DecryptMode, AES as IKey); var decodedBytes = c.DoFinal(obj.Value); return System.Text.Encoding.Unicode.GetString(decodedBytes); } catch (Exception) { return null; } } else if (obj.Type == EncryptType.STRONG) { try { Cipher c = Cipher.GetInstance ("RSA"); var k = obj.PublicKey as IKey; c.Init(Javax.Crypto.CipherMode.DecryptMode, obj.PrivateKey as IKey); var decodedBytes = c.DoFinal (obj.Value); return System.Text.Encoding.Unicode.GetString(decodedBytes); } catch (Exception) { return null; } } return null; }
public Password(String ClearPassword, int Salt) { m_ClearPassword = ClearPassword; m_Salt = Salt; m_SaltedPassword = Encrypt.ComputeSaltedHash(m_Salt, m_ClearPassword); }
public Card ValidarCartao(string number, string password) { var encriptedPassword = Encrypt.CriptografarSHA512(password); return(_repositoryCard.ValidarCartao(number, password)); }
void Sys_Member_Manage(HttpContext context) { #region 处理请求参数 string Id = context.Request["Id"]; int pkid = 0; if (!string.IsNullOrEmpty(Id)) { pkid = Convert.ToInt32(Id); } int DutyId = StringHelper.NullToInt(context.Request["DutyId"]); string AdminUser = StringHelper.NullToStr(context.Request["AdminUser"]); string AdminPassWord = StringHelper.NullToStr(context.Request["AdminPassWord"]); string AdminPassWordOld = StringHelper.NullToStr(context.Request["AdminPassWordOld"]); string Remark = StringHelper.NullToStr(context.Request["Remark"]); #endregion string jsonRet = ""; string retMsg = ""; UserInfo user = new UserInfo(); if (pkid < 1) { #region 添加操作 //判断用户名是否重复 DataSet ds = new BLL.Sys_Public().SelectData("top 1 ID,AUserName", "Sys_Admin", " and AUserName='******'"); if (ds != null && ds.Tables[0].Rows.Count > 0) { retMsg = "您输入的用户名已存在,请重新输入!"; jsonRet = "{retMsg:\"" + retMsg + "\"}"; context.Response.Write(retMsg); context.Response.End(); } Model.Sys_Admin sys_Model = new Model.Sys_Admin(); BLL.Sys_Admin sys_BLL = new BLL.Sys_Admin(); sys_Model.DutyID = DutyId; sys_Model.AUserName = AdminUser; sys_Model.TrueName = ""; sys_Model.Remark = Remark; sys_Model.APassWord = Encrypt.MakeSecuritySHA(AdminPassWord); sys_Model.CreateTime = DateTime.Now.ToLocalTime(); sys_Model.ModifyTime = DateTime.Now.ToLocalTime(); sys_Model.MoreCol1 = ""; sys_Model.MoreCol2 = ""; int ret = sys_BLL.Add(sys_Model); if (ret > 0) { retMsg = "添加成功"; jsonRet = "{retMsg:\"" + retMsg + "\"}"; } else { retMsg = "添加失败"; jsonRet = "{retMsg:\"" + retMsg + "\"}"; } context.Response.Write(retMsg); context.Response.End(); #endregion } else { #region 更新操作 Model.Sys_Admin sys_Model = new BLL.Sys_Admin().GetModel(pkid); BLL.Sys_Admin sys_BLL = new BLL.Sys_Admin(); sys_Model.ID = pkid; sys_Model.DutyID = DutyId; sys_Model.AUserName = AdminUser; sys_Model.TrueName = ""; sys_Model.Remark = Remark; if (AdminPassWord != "") { sys_Model.APassWord = Encrypt.MakeSecuritySHA(AdminPassWord); } else { sys_Model.APassWord = AdminPassWordOld; } sys_Model.ModifyTime = DateTime.Now.ToLocalTime(); sys_Model.MoreCol1 = ""; sys_Model.MoreCol2 = ""; bool ret = sys_BLL.Update(sys_Model); if (ret == true) { string tableName1 = "Sys_Admin"; string sqlWhere1 = " and AUserName='******' "; sqlWhere1 += " and APassWord='******'"; string showField1 = "top 1 Id,DutyID"; DataTable dt1 = new BLL.Sys_Public().SelectData(showField1, tableName1, sqlWhere1).Tables[0]; if (dt1 != null && dt1.Rows.Count > 0) { HttpCookie cookie = new HttpCookie("Fadmin"); cookie["DutyId"] = dt1.Rows[0]["DutyID"].ToString(); cookie["UserName"] = AdminUser; cookie["PassWord"] = AdminPassWord; HttpContext.Current.Response.Cookies.Add(cookie); Model.Sys_Logs logs = new Model.Sys_Logs(); logs.ID = 0; logs.DutyId = Utils.ToInt(dt1.Rows[0]["DutyID"].ToString()); logs.LoginName = AdminUser; logs.TitleName = "用户中心"; logs.Depicts = "用户密码修改,会员名为:" + AdminUser + ""; logs.CreateTime = DateTime.Now; logs.IpAddress = HttpContext.Current.Request.UserHostAddress; logs.MoreCol1 = ""; logs.MoreCol2 = ""; new BLL.Sys_Logs().Add(logs); } retMsg = "更新成功"; jsonRet = "{retMsg:\"" + retMsg + "\"}"; } else { retMsg = "更新失败"; jsonRet = "{retMsg:\"" + retMsg + "\"}"; } context.Response.Write(retMsg); context.Response.End(); #endregion } }
protected void CheckIfSettingsCorrect() { Identity = (string.IsNullOrWhiteSpace(Identity) || string.IsNullOrEmpty(Identity)) ? Encrypt.Md5Encrypt(Guid.NewGuid().ToString()) : Identity; UserId = (string.IsNullOrEmpty(UserId) || string.IsNullOrWhiteSpace(UserId)) ? "" : UserId; TaskGroup = (string.IsNullOrEmpty(TaskGroup) || string.IsNullOrWhiteSpace(TaskGroup)) ? "" : TaskGroup; if (Identity.Length > 100) { throw new SpiderException("Length of Identity should less than 100."); } if (UserId.Length > 100) { throw new SpiderException("Length of UserId should less than 100."); } if (TaskGroup.Length > 100) { throw new SpiderException("Length of TaskGroup should less than 100."); } if (PageProcessors == null || PageProcessors.Count == 0) { throw new SpiderException("Count of PageProcessor is zero."); } if (Site == null) { Site = new Site(); } Site.Accept = Site.Accept ?? "application/json, text/javascript, */*; q=0.01"; Site.UserAgent = Site.UserAgent ?? "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36"; if (!Site.Headers.ContainsKey("Accept-Language")) { Site.Headers.Add("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3"); } foreach (var processor in PageProcessors) { processor.Site = Site; } Scheduler = Scheduler ?? new QueueDuplicateRemovedScheduler(); Downloader = Downloader ?? new HttpClientDownloader(); }
public async Task <Unit> Handle(MerchantCommands request, CancellationToken cancellationToken) { if (!request.IsValid()) { // 错误信息收集 NotifyValidationErrors(request); // 返回,结束当前线程 return(await Task.FromResult(new Unit())); } var address = new Address(request.Province, request.City, request.County, request.Street); var Merchant = new Merchant(Guid.NewGuid(), request.MerchantName, request.Phone, request.BirthDate, request.MerchantIdCard, address, Encrypt.EncryptPassword(request.Password)); var iserror = await _MerchantRepository.GetByCardIdorName(Merchant.MerchantIdCard, Merchant.MerchantName); if (iserror != null) { await Bus.RaiseEvent(new DomainNotification("", "该身份证号或者用户名已经被使用!")); return(await Task.FromResult(new Unit())); } var count = await _MerchantRepository.AddModel(Merchant); if (count > 0) { if (Commit()) { // 提交成功后,这里需要发布领域事件 // 比如欢迎用户注册邮件呀,短信呀等 await Bus.RaiseEvent(new MerchantRegisteredEvent(Merchant.Id, Merchant.MerchantName, Merchant.BirthDate, Merchant.Phone, Merchant.MerchantIdCard)); } } return(await Task.FromResult(new Unit())); }
protected override void Page_Load(object sender, EventArgs e) { try { HttpCookie hc = getCookie("1"); if (hc != null) { string str = hc.Value.Replace("%3D", "="); userid = Encrypt.DecryptDES(str, "1"); user.load(userid); CheckRight(user.Entity, "pm/Base/ServiceType.aspx"); if (!Page.IsCallback) { if (user.Entity.UserType.ToUpper() != "ADMIN") { string sqlstr = "select a.RightCode from Sys_UserRight a left join sys_menu b on a.MenuId=b.MenuID " + "where a.UserType='" + user.Entity.UserType + "' and menupath='pm/Base/ServiceType.aspx'"; DataTable dt = obj.PopulateDataSet(sqlstr).Tables[0]; if (dt.Rows.Count > 0) { string rightCode = dt.Rows[0]["RightCode"].ToString(); if (rightCode.IndexOf("insert") >= 0) { Buttons += "<a href=\"javascript:;\" onclick=\"insert()\" class=\"btn btn-primary radius\"><i class=\"Hui-iconfont\"></i> 添加</a> "; } if (rightCode.IndexOf("update") >= 0) { Buttons += "<a href=\"javascript:;\" onclick=\"update()\" class=\"btn btn-primary radius\"><i class=\"Hui-iconfont\"></i> 修改</a> "; } if (rightCode.IndexOf("delete") >= 0) { Buttons += "<a href=\"javascript:;\" onclick=\"del()\" class=\"btn btn-danger radius\"><i class=\"Hui-iconfont\"></i> 删除</a> "; } if (rightCode.IndexOf("vilad") >= 0) { Buttons += "<a href=\"javascript:;\" onclick=\"valid()\" class=\"btn btn-primary radius\"><i class=\"Hui-iconfont\"></i> 启用/停用</a> "; } } } else { Buttons += "<a href=\"javascript:;\" onclick=\"insert()\" class=\"btn btn-primary radius\"><i class=\"Hui-iconfont\"></i> 添加</a> "; Buttons += "<a href=\"javascript:;\" onclick=\"update()\" class=\"btn btn-primary radius\"><i class=\"Hui-iconfont\"></i> 修改</a> "; Buttons += "<a href=\"javascript:;\" onclick=\"del()\" class=\"btn btn-danger radius\"><i class=\"Hui-iconfont\"></i> 删除</a> "; Buttons += "<a href=\"javascript:;\" onclick=\"valid()\" class=\"btn btn-primary radius\"><i class=\"Hui-iconfont\"></i> 启用/停用</a> "; } list = createList(string.Empty, string.Empty); SRVSPNoStr = "<select class=\"input-text required\" id=\"SRVSPNo\" data-valid=\"between:0-30\" data-error=\"\">"; SRVSPNoStr += "<option value=\"\" selected>请选择服务商</option>"; Business.Base.BusinessServiceProvider tp = new project.Business.Base.BusinessServiceProvider(); foreach (Entity.Base.EntityServiceProvider it in tp.GetListQuery(string.Empty, string.Empty, true)) { SRVSPNoStr += "<option value='" + it.SPNo + "'>" + it.SPName + "</option>"; } SRVSPNoStr += "</select>"; } } else { Response.Write(errorpage); return; } } catch { Response.Write(errorpage); return; } }
public ActionResult ServiceDetails(string memid = "") { if (Session["WhiteLevelUserId"] != null) { initpage(); try { var db = new DBContext(); long UserId = MemberCurrentUser.MEM_ID; if (memid != "") { string decrptSlId = Decrypt.DecryptMe(memid); long Memid = long.Parse(decrptSlId); var userinfo = db.TBL_MASTER_MEMBER.FirstOrDefault(x => x.MEM_ID == Memid); ViewBag.decrptSlId = Encrypt.EncryptMe(Memid.ToString()); var memberinfo = (from x in db.TBL_WHITELABLE_SERVICE join y in db.TBL_SETTINGS_SERVICES_MASTER on x.SERVICE_ID equals y.SLN join w in db.TBL_MASTER_MEMBER on x.MEMBER_ID equals w.MEM_ID where x.MEMBER_ID == Memid && y.ACTIVESTATUS == true select new { Member_ID = x.MEMBER_ID, UserName = w.UName, ServiceName = y.SERVICE_NAME, SLN = x.SL_NO, ActiveService = x.ACTIVE_SERVICE }).AsEnumerable().Select(z => new TBL_WHITELABLE_SERVICE { MEMBER_ID = z.Member_ID, UserName = z.UserName, ServiceName = z.ServiceName, SL_NO = z.SLN, ACTIVE_SERVICE = z.ActiveService }).ToList(); ViewBag.checkVal = "1"; var memberService = (from x in db.TBL_MASTER_MEMBER where x.CREATED_BY == UserId select new { MEM_ID = x.MEM_ID, UName = x.MEMBER_NAME }).AsEnumerable().Select(z => new MemberView { IDValue = Encrypt.EncryptMe(z.MEM_ID.ToString()), TextValue = z.UName }).ToList().Distinct(); ViewBag.MemberService = new SelectList(memberService, "IDValue", "TextValue"); return(View(memberinfo)); } else { var memberService = (from x in db.TBL_MASTER_MEMBER where x.CREATED_BY == UserId select new { MEM_ID = x.MEM_ID, UName = x.MEMBER_NAME }).AsEnumerable().Select(z => new MemberView { IDValue = Encrypt.EncryptMe(z.MEM_ID.ToString()), TextValue = z.UName }).ToList().Distinct(); ViewBag.MemberService = new SelectList(memberService, "IDValue", "TextValue"); ViewBag.checkVal = "0"; var memberinfo = new List <TBL_WHITELABLE_SERVICE>(); return(View(memberinfo)); } //return View(); } catch (Exception ex) { Logger.Error("Controller:- MemberService(Admin), method:- ServiceDetails (GET) Line No:- 158", ex); return(RedirectToAction("Exception", "ErrorHandler", new { area = "" })); throw ex; } } else { Session["WhiteLevelUserId"] = null; Session["WhiteLevelUserName"] = null; Session["UserType"] = null; Session.Remove("WhiteLevelUserId"); Session.Remove("WhiteLevelUserName"); Session.Remove("UserType"); return(RedirectToAction("Index", "AdminLogin", new { area = "Admin" })); } }
public Password(String ClearPassword) { m_ClearPassword = ClearPassword; m_Salt = Encrypt.CreateRandomSalt(); m_SaltedPassword = Encrypt.ComputeSaltedHash(m_Salt, m_ClearPassword); }
public async Task <User> GetUserByNameAndPasswordAsync(string userMail, string userPassword) { //var passwordHash = Encrypt.GetSHA256(userPassword); return(await FindByCondition(user => user.UserMail.Equals(userMail) && user.UserPassword.Equals(Encrypt.GetSHA256(userPassword))) .FirstOrDefaultAsync()); }
public RandomStrongPassword() : base(Encrypt.CreateRandomStrongPassword(ro_RandomStrongPasswordLength), Encrypt.CreateRandomSalt()) { }
private byte[] getCiphertext(MessageKeys messageKeys, byte[] plaintext) { return(Encrypt.aesCbcPkcs5(plaintext, messageKeys.getCipherKey(), messageKeys.getIv())); }
public async Task <ActionResult> Index(LoginViewModel User, string ReturnURL = "") { SystemClass sclass = new SystemClass(); ////// string userID = sclass.GetLoggedUser(); ////var userpass = "******"; ////userpass = userpass.GetPasswordHash(); //if (Session["SuperDistributorId"] == null || Session["DistributorUserId"] == null) //{ using (var db = new DBContext()) { var GetMember = await db.TBL_MASTER_MEMBER.SingleOrDefaultAsync(x => x.EMAIL_ID == User.Email && x.User_pwd == User.Password && x.MEMBER_ROLE == 5 && x.ACTIVE_MEMBER == true); if (GetMember != null) { if (GetMember.ACTIVE_MEMBER == false || GetMember.User_pwd != User.Password) { ViewBag.Message = "Invalid Credential or Access Denied"; //ViewBag.Islogin = false; return(View()); } else { Session["MerchantUserId"] = GetMember.MEM_ID; Session["MerchantUserName"] = GetMember.UName; //ViewBag.Islogin = true; //var walletamount = db.TBL_ACCOUNTS.Where(x => x.MEM_ID == GetMember.MEM_ID).OrderByDescending(z => z.TRANSACTION_TIME).FirstOrDefault(); //if (walletamount != null) //{ // ViewBag.openingAmt = walletamount.OPENING; // ViewBag.closingAmt = walletamount.CLOSING; //} //else //{ // ViewBag.openingAmt = "0"; // ViewBag.closingAmt = "0"; //} Session["UserType"] = "Merchant"; HttpCookie AuthCookie; System.Web.Security.FormsAuthentication.SetAuthCookie(GetMember.UName + "||" + Encrypt.EncryptMe(GetMember.MEM_ID.ToString()), true); AuthCookie = System.Web.Security.FormsAuthentication.GetAuthCookie(GetMember.UName + "||" + Encrypt.EncryptMe(GetMember.MEM_ID.ToString()), true); AuthCookie.Expires = DateTime.Now.Add(new TimeSpan(130, 0, 0, 0)); Response.Cookies.Add(AuthCookie); return(RedirectToAction("Index", "MerchantDashboard", new { area = "Merchant" })); //Response.Redirect(FormsAuthentication.GetRedirectUrl(GetUser.USER_NAME.ToString(), true)); } } else { ViewBag.Message = "Invalid Credential or Access Denied"; return(View()); } } //} //else //{ // Response.RedirectToRoute("Home", "Index"); //} return(View()); }
public TCrypterOutput InvokeEncrypt(params TInput[] input) { return((TCrypterOutput)Encrypt.Invoke(CryptorObject, input)); }
/// <summary> /// 登录按钮事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnLogin_Click(object sender, EventArgs e) { try { #region 根据用户输入的服务其地址进行连接相对应的服务 string errMsg = ""; mdiMainForm mainForm = new mdiMainForm(); bool isSuccess = mainForm.Initialize(txtTradeID.Text.Trim(), ref errMsg); if (!isSuccess) { //errMsg = ResourceOperate.Instanse.GetResourceByKey("WCF"); error.SetError(txtPassword, errMsg); return; } #endregion 根据用户输入的服务其地址进行连接相对应的服务 #region 对用户输入的信息进行判断,并在判断通过时保存到配置文件中 if (!string.IsNullOrEmpty(this.txtTradeID.Text)) { #region 对资金帐户的长度和输入格式进行判断 #region 判断文本框中数据是否与APP中数据是否相等,如果相等则不修改APP中数据,否则修改APP中数据 string Password = this.txtPassword.Text; int userId; if (!string.IsNullOrEmpty(Password)) { #region 对TraderID进行判断 string message; //将用户输入的密码进行加密,否则与数据库中加密过的密码进行比较会出现密码验证错误 string password = Encrypt.DesEncrypt(Password, string.Empty); //对用户输入的TradeId进行判断,如果查询出柜台说明该用户是交易员,否则进行管理员判断 int.TryParse(this.txtTradeID.Text.Trim(), out userId); GTA.VTS.CustomersOrders.TransactionManageService.CT_Counter counter = wcfLogic.TransactionConfirm(userId, password, out message); if (counter == null) { string LoginName = this.txtTradeID.Text.Trim(); string Loginerror = ResourceOperate.Instanse.GetResourceByKey("Loginerror"); #region 管理员验证 string messages; bool result = wcfLogic.AdminConfirmation(LoginName, password, out messages); if (!result) { error.Clear(); error.SetError(txtPassword, Loginerror); return; } ServerConfig.TraderID = LoginName; ServerConfig.PassWord = password; ServerConfig.Refresh(); this.DialogResult = DialogResult.OK; this.Close(); #endregion 管理员验证 } else { int counterID = counter.CouterID; int trade; if (int.TryParse(txtTradeID.Text, out trade)) { Capitalaccount(counterID, trade); ServerConfig.PassWord = password; ServerConfig.TraderID = txtTradeID.Text.Trim(); ServerConfig.Refresh(); this.DialogResult = DialogResult.OK; this.Close(); } else { error.Clear(); string errors = ResourceOperate.Instanse.GetResourceByKey("TradeError"); error.SetError(txtPassword, errors); return; } } #endregion 对TraderID进行判断 } else { error.Clear(); string errors = ResourceOperate.Instanse.GetResourceByKey("errors"); error.SetError(txtPassword, errors); return; } #endregion 判断文本框中数据是否与APP中数据是否相等,如果相等则不修改APP中数据,否则修改APP中数据 #endregion 对资金帐户的长度和输入格式进行判断 } else { error.Clear(); string TradeIDerror = ResourceOperate.Instanse.GetResourceByKey("TradeIDerror"); error.SetError(txtTradeID, TradeIDerror); return; } #endregion } catch (Exception ex) { LogHelper.WriteError(ex.Message, ex); } }
/// <summary> /// 签名 /// </summary> public string Sign() { var value = $"{_builder.Result( true )}&key={_key.GetKey()}"; return(Encrypt.HmacSha256(value, _key.GetKey()).ToUpper()); }
public ActionResult AddOrUpdateEmployee(EmployeeViewModel employeeViewModel) { bool result = false; var msg = ""; try { #region Bas_Employee Bas_Employee bas_Employee = null; if (employeeViewModel.Id > 0) { bas_Employee = employeeBll.GetEmployeeEntity(employeeViewModel.Id); if (bas_Employee == null) { throw new AbhsException(ErrorCodeEnum.ParameterInvalid, AbhsErrorMsg.ConstParameterInvalid); } } if (bas_Employee == null) { bas_Employee = new Bas_Employee(); } bas_Employee.Bem_Id = employeeViewModel.Id; bas_Employee.Bem_Account = employeeViewModel.Account; if (employeeViewModel.Password.HasValue()) { bas_Employee.Bem_Password = Encrypt.GetMD5Pwd(employeeViewModel.Password); } bas_Employee.Bem_Name = employeeViewModel.Name; bas_Employee.Bem_Sex = employeeViewModel.Sex; bas_Employee.Bem_Phone = employeeViewModel.Phone; bas_Employee.Bem_Email = employeeViewModel.Email; bas_Employee.Bem_Roles = employeeViewModel.Roles; bas_Employee.Bem_Status = employeeViewModel.Status; bas_Employee.Bem_Remark = employeeViewModel.Remark; bas_Employee.Bem_Grades = employeeViewModel.Grades.Sum(); #endregion Bas_EmployeeRole bas_EmployeeRole = new Bas_EmployeeRole(); if (bas_Employee.Bem_Id == 0) { bas_Employee.Bem_CreateTime = DateTime.Now; bas_Employee.Bem_Editor = CurrentUserID; bas_Employee.Bem_LastLoginTime = DateTimeExtensions.DefaultDateTime; bas_EmployeeRole.Ber_CreateTime = DateTime.Now; bas_EmployeeRole.Ber_Creator = CurrentUserID; result = employeeBll.AddEmployee(bas_Employee, bas_EmployeeRole); } else { bas_Employee.Bem_UpdateTime = DateTime.Now; bas_Employee.Bem_Editor = CurrentUserID; bas_EmployeeRole.Ber_CreateTime = DateTime.Now; bas_EmployeeRole.Ber_Creator = CurrentUserID; result = employeeBll.UpdateEmployee(bas_Employee, bas_EmployeeRole); } } catch (Exception ex) { msg = "异常,请重试"; //return Json(new JsonSimpleResponse() { State = false, ErrorMsg = ex.Message }); } msg = result ? "操作成功" : "操作失败"; return(Json(new JsonSimpleResponse() { State = result, ErrorMsg = msg })); }
/// <summary> /// 签名 /// </summary> public string Sign() { return(Encrypt.Rsa2Sign(_builder.Result(true), _key.GetKey())); }
private static void Handle_Encrypt ( Shell Dispatch, string[] args, int index) { Encrypt Options = new Encrypt (); var Registry = new Goedel.Registry.Registry (); #pragma warning disable 162 for (int i = index; i< args.Length; i++) { if (!IsFlag (args [i][0] )) { throw new System.Exception ("Unexpected parameter: " + args[i]);} string Rest = args [i].Substring (1); TagType_Encrypt TagType = (TagType_Encrypt) Registry.Find (Rest); // here have the cases for what to do with it. switch (TagType) { default : throw new System.Exception ("Internal error"); } } #pragma warning restore 162 Dispatch.Encrypt (Options); }
/// <summary> /// 验证签名 /// </summary> /// <param name="sign">签名</param> public bool Verify(string sign) { return(Encrypt.Rsa2Verify(_builder.Result(true), _key.GetPublicKey(), sign)); }
//投快递 private void button_SendPKG_Click(object sender, EventArgs e) { string SD_usr_phone = textBox_SD_usr_phone.Text.Trim(); string SD_exp_no = textBox_SD_express_No.Text.Trim(); string SD_usr_name = "王"; string boxDX = comboBox_size.Text.Trim(); if(SD_usr_phone=="" || SD_exp_no=="") //输入规则检查 { label_SendPKG_status.Text = "输入有误,请重新输入!"; return ; } if (textBox_SD_usr_name.Text.Trim() != "") { SD_usr_name = textBox_SD_usr_name.Text.Trim(); } //返回合适的空箱子 boxDX = "1"; string BoxID=MyBox.FindBox(boxDX); if (BoxID == "") //无合适箱子 { label_SendPKG_status.Text = "该规格箱子已满,请重新选择!"; } else { //打开箱子 if(MyBox.OpenBox(BoxID)) //打开成功,成功存包 { #region //语音提示 //产生8位随机提取码 Encrypt eBoxEncrypt=new Encrypt(); string SD_usr_Code=eBoxEncrypt.GenUserCode(); DateTime TimeNow= System.DateTime.Now.ToLocalTime(); try { OleCon = new OleDbConnection(strcon); OleCon.Open(); //更新存包记录数据库 string sql = String.Format("Insert into PKG_RECORD(Ebox_No,User_phone,User_Code,Postman_No,Box_ID,Time_Save,Exp_Num) Values('{0}','{1}','{2}','{3}','{4}',#{5:G}#,'{6}')", Ebox_No, SD_usr_phone, SD_usr_Code, Login_PSTM_phone, BoxID, TimeNow, SD_exp_no); OleCom = new OleDbCommand(sql, OleCon); int PassOk = OleCom.ExecuteNonQuery(); Console.WriteLine(PassOk); //更新箱子信息数据库 //更新box_manage数据库,设置对应箱子为满 sql = "Update BOX_MANAGE Set BOX_MANAGE.Empty_State=false,BOX_MANAGE.Time_update=#" +TimeNow + "# where BOX_MANAGE.Box_ID='" + BoxID + "'"; OleCom = new OleDbCommand(sql, OleCon); int ReturnVal = OleCom.ExecuteNonQuery(); Console.WriteLine(ReturnVal); } catch(Exception ex) { MessageBox.Show(ex.ToString()); } finally { OleCon.Close(); } //更新空箱数 Box_Num_used += 1; Box_Used_amount += 1; //更新快递员余额数据库 ebox_webservice.ebox_serviceSoapClient ebox_webserver = new ebox_webservice.ebox_serviceSoapClient(); Login_PSTM_balance=ebox_webserver.Postman_Spend(Login_PSTM_phone,1); toolStripStatusLabel1.Text = "快递员:" + Login_PSTM_phone + ", 欢迎您! 余额:" + Login_PSTM_balance.ToString(); //超时计时开始 label_SendPKG_status.Text = BoxID+"箱已打开,请存入包裹,关好箱门!"; textBox_SD_usr_phone.Text = ""; textBox_SD_express_No.Text = ""; ShowEboxStatus(); #endregion } else //打开失败 { label_SendPKG_status.Text = "打开箱子失败,请重新选择!"; } } }
private void timer1_Tick(object sender, EventArgs e) { //1秒跑一次的程序 if (AllowTakeOrderBool == true) { if (button1.Enabled == false) { button1.Enabled = true; } } //1秒跑一次的程序2 if (richTextBox1.Text.Contains("\n")) { if (foodDic.Count == 0) { richTextBox1.Clear(); MessageBox.Show("请选择至少一个菜品"); return; } try { //解析扫码数据,拿取关键信息 var richText = richTextBox1.Text.Split('\n'); //二维码解码 var jsonText = Encrypt.Decode(richText[0]); //json数据格式整理 JavaScriptObject jsonObj = JavaScriptConvert.DeserializeObject <JavaScriptObject>(jsonText); Temp_pcNum = jsonObj["Num"].ToString(); personId = jsonObj["Id"].ToString(); staffEnum = jsonObj["staffEnum"].ToString(); var personCardId = jsonObj["Num"].ToString();//身份证号码 //如果是家属 则return if (staffEnum == "Family") { richTextBox1.Text = ""; MessageBox.Show("家属不可打包"); return; } //检查是否存在这个人 Object o_result = null; //检查是否存在这个人 //DataRow[] selectedResult = PcTable.Select("Id=" + personId); if (staffEnum == "Police") { string select_Exist_pc = "select * from Cater.PCStaff where [Id]='" + personId + "'"; o_result = SqlHelper.ExecuteScalar(select_Exist_pc); } else { string select_Exist_worker = "select * from Cater.WorkerStaff where [Id]='" + personId + "'"; o_result = SqlHelper.ExecuteScalar(select_Exist_worker); } if (o_result == null) { richTextBox1.Text = ""; label2.Font = new Font("宋体粗体", 30); label2.ForeColor = Color.Red; label2.Text = "查无此人"; OrderFoodList.Clear(); OrderFoodPrice.Clear(); // ButtonNumClear(); foodDic.Clear(); Refresh(); return; } //查看是否过期以及余额是否足够 string imforUrl = null; if (staffEnum == "Police") { imforUrl = "http://" + Properties.Settings.Default.header_url + @"/Interface/PC/GetPcStaff.ashx?InformationNum=" + personCardId; } else { imforUrl = "http://" + Properties.Settings.Default.header_url + "/Interface/Worker/GetWorkerStaff.ashx?informationNum=" + personCardId; } string dateResponse = ""; try { dateResponse = GetFunction(imforUrl);//照片url回复 } catch (Exception ex) { richTextBox1.Text = ""; label2.Text = "网络错误"; OrderFoodList.Clear(); OrderFoodPrice.Clear(); //ButtonNumClear(); foodDic.Clear(); Refresh(); return; } JavaScriptObject jsonResponse2 = JavaScriptConvert.DeserializeObject <JavaScriptObject>(dateResponse); JavaScriptObject json; if (jsonResponse2["Msg"].ToString() == "失败") { richTextBox1.Text = ""; label2.Text = "账号验证失败"; OrderFoodList.Clear(); OrderFoodPrice.Clear(); //ButtonNumClear(); foodDic.Clear(); Refresh(); return; } if (staffEnum == "Police") { json = (JavaScriptObject)jsonResponse2["pcInfo"]; } else { json = (JavaScriptObject)jsonResponse2["workerInfo"]; } var effectDate = json["ValidityDate"]; if (effectDate != null) { TimeSpan ts = Convert.ToDateTime(effectDate.ToString().Split('T')[0]) - DateTime.Now; if (ts.Hours < 0) { label2.Text = "用户已过期!"; richTextBox1.Text = ""; SpeechVideo_Read(0, 100, "用户已过期!"); OrderFoodList.Clear(); OrderFoodPrice.Clear(); foodDic.Clear(); Refresh(); //ButtonNumClear(); return; } } string money = json["Amount"].ToString(); if ((Convert.ToDouble(money) - Convert.ToDouble(priceSum())) < 0) { label2.Text = "余额不足!"; richTextBox1.Text = ""; SpeechVideo_Read(0, 100, "余额不足!"); OrderFoodList.Clear(); OrderFoodPrice.Clear(); //ButtonNumClear(); foodDic.Clear(); Refresh(); return; } //显示扫码成功!大字体 richTextBox1.Text = ""; label2.Font = new Font("宋体粗体", 30); label2.ForeColor = Color.Green; label2.Text = "扫码成功!"; SpeechVideo_Read(0, 100, "扫码成功!"); //ButtonNumClear(); //扫码成功写入数据库 string foodstring = null; foreach (var item in foodDic) { var str = item.Key; str = str.Substring(0, str.Length - 1); //定义正则表达式规则 Regex reg = new Regex(@"\d+\.\d+"); //返回一个结果集,找出菜名字! MatchCollection result = reg.Matches(str); str = str.Replace(result[0].Value, ""); //查数据库找出detailID var selectID = SqlHelper.ExecuteScalar(@"SELECT [Id] FROM[XinYuSiteDB].[Cater].[CookbookSetInDateDetail] where CookbookDateId = '" + TempOrderId + "' and CookbookName = '" + str + "'"); foodstring += selectID + ","; } foodstring = foodstring.Substring(0, foodstring.Length - 1); //计算总价 string orderPrice = priceSum(); InsertRecoed(staffEnum, personId, whole_catlocation.ToString(), TempOrderId.ToString(), foodstring, orderPrice, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); //还原buuton的enable状态! Return_Button(); //清楚已选列表 OrderFoodList.Clear(); OrderFoodPrice.Clear(); foodDic.Clear(); Refresh(); } catch (Exception EX) { // MessageBox.Show(EX.Message); richTextBox1.Text = ""; // MessageBox.Show(EX.Message); label2.Text = "请出示正确的二维码"; SpeechVideo_Read(0, 100, "扫码错误!"); OrderFoodList.Clear(); OrderFoodPrice.Clear(); //ButtonNumClear(); Return_Button(); } //写入文本,写入记录 } }
public Encrypt Encode(EncryptType type, string value) { var result = new Encrypt (); result.Value = null; result.Type = type; if (type == EncryptType.OK) { try { var key = AES; if (key != null) { result.Key = key; Cipher c = Cipher.GetInstance("AES"); c.Init(CipherMode.EncryptMode, key as IKey); var encoder = new System.Text.UnicodeEncoding(); result.Value = c.DoFinal(encoder.GetBytes(value)); return result; } } catch (Exception) { return null; } } else if (type == EncryptType.STRONG) { try { var keys = RSA; if (keys != null) { result.PublicKey = keys[1]; result.PrivateKey = keys[0]; Cipher c = Cipher.GetInstance ("RSA"); c.Init(Javax.Crypto.CipherMode.EncryptMode, result.PublicKey as IKey); var encoder = new System.Text.UnicodeEncoding(); result.Value = c.DoFinal (encoder.GetBytes(value)); return result; } } catch (Exception) { return null; } } return null; }
private void MainWindow_Load(object sender, EventArgs e) { Enabled = false; BuildMenuStrip(); var currentLanguage = Localization.GetCurrentLanguage(); ChangeLanguage(currentLanguage); try { _encrypt = new Encrypt(); } catch (Exception ex) { MessageBox.Show(ex.Message, ErrorString, MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); } MainWindow_Resize(sender, e); Enabled = true; }