public bool SaveUser(UserModel userModel, bool IsChangePwd = false) { if (string.IsNullOrWhiteSpace(userModel.UserCode)) { userModel.UserCode = Guid.NewGuid().ToString(); userModel.PassWord = EncryptTool.GetMd5By32("123456"); return(_userRepository.CreateModel(userModel) > 0); } else { var model = _userRepository.GetModelByCode(userModel.UserCode); model.DisplayName = userModel.DisplayName; model.Sex = userModel.Sex; model.Phone = userModel.Phone; model.RoleCode = userModel.RoleCode; model.ModifyDate = userModel.ModifyDate; model.ModifyDisplayName = userModel.ModifyDisplayName; model.ModifyUserName = userModel.ModifyUserName; if (IsChangePwd) { model.PassWord = EncryptTool.GetMd5By32(userModel.PassWord); } return(_userRepository.UpdateModel(model) > 0); } }
public void RevisePassword(string userPassword, string keyValue, string userId) { FrameUserModel frameUserModel = frameUserDAO.GetById(keyValue); frameUserModel.F_UserPassword = EncryptTool.MD5Encrypt64(userPassword); frameUserDAO.Update(frameUserModel, userId); }
protected void btnOk_Click(object sender, EventArgs e) { ParamFacade facade = new ParamFacade(); ParamInfo param = facade.GetParam("AdministratorPassword"); string oldPassword = EncryptTool.MD5(txtOldPassword.Text); string newPassword = EncryptTool.MD5(txtNewPassword.Text); string confirmPassword = EncryptTool.MD5(txtConfirmPassword.Text); if (newPassword != confirmPassword) { lblMessage.Text = "两次输入的密码不相同。"; return; } if (param == null || string.IsNullOrEmpty(param.Value) || param.Value == oldPassword) { param = new ParamInfo(); param.Key = "AdministratorPassword"; param.Value = newPassword; facade.SaveParam(param); string url = "Default.aspx"; if (!string.IsNullOrEmpty(Request["ReturnUrl"])) { url = Request["ReturnUrl"]; } string msg = "修改密码成功!"; ScriptManager.RegisterStartupScript(this, this.GetType(), "AlertChangePassword", "AlertAndRedirect('" + msg + "', '" + url + "');", true); } else { lblMessage.Text = "旧密码输入不正确。"; return; } }
public UserInfo Login(string userId, string password) { try { UserManager manager = new UserManager(DbAccess); password = EncryptTool.MD5(password); LoginEntity entity = manager.Authenticate(userId, password); ObjectPersistence persistence = new ObjectPersistence(DbAccess); return(persistence.GetByKey <UserInfo>(userId)); } catch (LoginException ex) { string errMsg = "登录失败"; switch (ex.LoginErrorType) { case LoginErrorType.UserIdOrPasswordError: errMsg += " - 输入的用户名或密码错误!"; break; case LoginErrorType.UserCannotLogin: errMsg += " - 用户被限制登录,请联系系统管理员!"; break; } throw HandleException(LogCategory.Login, errMsg, ex); } catch (Exception ex) { string errMsg = "登录失败 - 系统异常,请联系系统管理员!"; throw HandleException(LogCategory.Login, errMsg, ex); } }
/// <summary> /// get cookie /// </summary> /// <typeparam name="T">value type</typeparam> /// <param name="key">cookie key</param> /// <returns>cookie value</returns> public static T GetCookie <T>(string key) { if (System.Web.HttpContext.Current.Request.Cookies.AllKeys.Contains(key)) { string val = System.Web.HttpContext.Current.Request.Cookies[key].Value; if (string.IsNullOrWhiteSpace(val)) { return(default(T)); } else { try { val = EncryptTool.Base64Decode(val); return(JsonConvert.DeserializeObject <T>(val)); } catch (Exception ex) { LogTool.Error(ex); return(default(T)); } } } else { System.Web.HttpContext.Current.Response.Redirect("/"); System.Web.HttpContext.Current.Response.End(); return(default(T)); } }
/// <summary> /// Encrypt packet /// </summary> /// <param name="packet"></param> /// <returns></returns> protected string EncryptPacket(Packet packet) { var str = packet.SerializeAsJson(); var encrypted = EncryptTool.Encrypt(str, GlobalResources.SecretKey); return(encrypted); }
protected string GetUserNamePasswordFromTK(string tk) { string username1 = EncryptTool.Decrypt(tk, MyCustomMessageHandler.SecretGuid, false); if (username1.StartsWith("WeChatUserName:"******"无效的", WeChatTokenQueryStringName)); }
public void AddUser() { var db = new CrossContext(); db.Users.Add(new IdentityUser <int> { NormalizedUserName = "******", NormalizedEmail = "*****@*****.**", PasswordHash = EncryptTool.Encrypt("123456") }); db.SaveChanges(); }
public void AddLogin(LoginEntity loginEntity, string password) { UserPassowrdEntity pwdEntity = new UserPassowrdEntity(); pwdEntity.UserId = loginEntity.UserId; pwdEntity.UserName = loginEntity.UserName; pwdEntity.IsCanLogin = loginEntity.IsCanLogin; pwdEntity.RegisterTime = DateTime.Now; pwdEntity.Password = EncryptTool.MD5(password); persistence.Add(pwdEntity); }
/// <summary> /// add cookie /// </summary> /// <param name="key">cookie key</param> /// <param name="val">cookie value</param> public static void AddCookie(string key, object val) { HttpCookie cookie = new HttpCookie(key); cookie.Value = EncryptTool.Base64Encode(JsonConvert.SerializeObject(val)); if (System.Web.HttpContext.Current.Request.Cookies.AllKeys.Contains(key)) { HttpCookie cookieExist = System.Web.HttpContext.Current.Request.Cookies[key]; cookieExist.Expires = DateTime.Now.AddDays(-3); } System.Web.HttpContext.Current.Response.Cookies.Add(cookie); }
public ActionResult GetGridJson(Pagination pagination, string keyword) { HttpContext.Request.Cookies.TryGetValue("jxkbd20180822", out string value); var operatorModel = EncryptTool.DESDecrypt(value).ToObject <OperatorModel>(); var data = new { rows = frameUserService.GetList(keyword, pagination), total = pagination.total, page = pagination.page, records = pagination.records }; return(Content(data.ToJson())); }
/// <summary> /// convert parameter string into key value /// </summary> /// <param name="pmsStr">parameter string</param> /// <returns>parameter key value</returns> public static Dictionary <string, object> ConvertPms(string pmsStr) { if (string.IsNullOrWhiteSpace(pmsStr)) { return(null); } try { return(JsonConvert.DeserializeObject <Dictionary <string, object> >(EncryptTool.UrlDecode(pmsStr))); } catch { return(null); } }
public ActionResult GetClientsDataJson() { HttpContext.Request.Cookies.TryGetValue("jxkbd20180822", out string value); var operatorModel = EncryptTool.DESDecrypt(value).ToObject <OperatorModel>(); var data = new { dataItems = this.GetDataItemList(), organize = this.GetOrganizeList(), role = this.GetRoleList(), duty = this.GetDutyList(), user = "", authorizeMenu = this.GetMenuList(), authorizeButton = this.GetMenuButtonList(), }; return(Content(data.ToJson())); }
/// <summary> /// Get user name from token /// </summary> /// <param name="token"></param> /// <returns></returns> public User GetUserFromToken(string token) { if (token.IsNullOrEmpty()) { return(null); } var basicStr = EncryptTool.Decrypt(token, GlobalResources.SecretKey); if (basicStr.IsNullOrEmpty()) { return(null); } var spl = basicStr.Split(":"); var user = spl[0]; var pass = spl[1]; return(InMemoryUsers.Users.FirstOrDefault(x => x.UserName.Equals(user) && x.Password.Equals(pass))); }
protected void btnLogin_Click(object sender, EventArgs e) { string password = EncryptTool.MD5(txtPassword.Text); ParamInfo param = DataCache.GetParam(this.Page, "AdministratorPassword"); if (param != null && param.Value == password) { IsAdminLogined = true; string url = "Default.aspx"; if (!string.IsNullOrEmpty(Request["ReturnUrl"])) { url = Request["ReturnUrl"]; } RedirectToUrl(url); } else { lblMessage.Text = "密码错误!"; } }
private void method_0(SurveyMain surveyMain_0) { this.oSurveyAnswerDal.AddOne(surveyMain_0.SURVEY_ID, "SURVEY_ID", surveyMain_0.SURVEY_ID, 0); this.oSurveyAnswerDal.AddOne(surveyMain_0.SURVEY_ID, GClass0.smethod_0("\\Ōɚ͔яՊيݜࡋॅ"), surveyMain_0.VERSION_ID, 0); this.oSurveyAnswerDal.AddOne(surveyMain_0.SURVEY_ID, GClass0.smethod_0("Rŕɀ͖ќՋم"), surveyMain_0.USER_ID, 0); this.oSurveyAnswerDal.AddOne(surveyMain_0.SURVEY_ID, GClass0.smethod_0("Dŏɑ͝ќՋم"), surveyMain_0.CITY_ID, 0); this.oSurveyAnswerDal.AddOne(surveyMain_0.SURVEY_ID, GClass0.smethod_0("Yŝɉ͕ђ՚ِ݊ࡏॄ"), surveyMain_0.START_TIME.ToString(), 0); this.oSurveyAnswerDal.AddOne(surveyMain_0.SURVEY_ID, GClass0.smethod_0("Mʼnɂ͚ѐՊُ݄"), surveyMain_0.END_TIME.ToString(), 0); this.oSurveyAnswerDal.AddOne(surveyMain_0.SURVEY_ID, GClass0.smethod_0("Cŏɞ͘єՙٝ݉ࡕ॒ਗ਼ొ൏ไ"), surveyMain_0.LAST_START_TIME.ToString(), 0); this.oSurveyAnswerDal.AddOne(surveyMain_0.SURVEY_ID, GClass0.smethod_0("Aōɘ͞іՍى݂࡚ॐౄ"), surveyMain_0.LAST_END_TIME.ToString(), 0); this.oSurveyAnswerDal.AddOne(surveyMain_0.SURVEY_ID, GClass0.smethod_0("Hşɛ͗їՇق݁ो"), surveyMain_0.CUR_PAGE_ID, 0); this.oSurveyAnswerDal.AddOne(surveyMain_0.SURVEY_ID, GClass0.smethod_0("Sņɜ͎рՎٕ݈ࡗॄୗౖെ์ཕ"), surveyMain_0.CIRCLE_A_CURRENT.ToString(), 0); this.oSurveyAnswerDal.AddOne(surveyMain_0.SURVEY_ID, GClass0.smethod_0("Mńɞ͈цՌ݆࡙ٗॆੋୖౌൕ"), surveyMain_0.CIRCLE_A_COUNT.ToString(), 0); this.oSurveyAnswerDal.AddOne(surveyMain_0.SURVEY_ID, GClass0.smethod_0("Sņɜ͎рՎٕࡗॄୗౖെ์ཕ"), surveyMain_0.CIRCLE_B_CURRENT.ToString(), 0); this.oSurveyAnswerDal.AddOne(surveyMain_0.SURVEY_ID, GClass0.smethod_0("Mńɞ͈цՌ࡙ٗ݅ॆੋୖౌൕ"), surveyMain_0.CIRCLE_B_COUNT.ToString(), 0); this.oSurveyAnswerDal.AddOne(surveyMain_0.SURVEY_ID, GClass0.smethod_0("@śɘ̀ьՊيݑࡉ"), surveyMain_0.IS_FINISH.ToString(), 0); this.oSurveyAnswerDal.AddOne(surveyMain_0.SURVEY_ID, GClass0.smethod_0("Xŏɘ͝тՈن݁ो"), surveyMain_0.SEQUENCE_ID.ToString(), 0); this.oSurveyAnswerDal.AddOne(surveyMain_0.SURVEY_ID, GClass0.smethod_0("Xşɛ͞т՟ٚ݃ࡖो"), surveyMain_0.SURVEY_GUID, 0); this.oSurveyAnswerDal.AddOne(surveyMain_0.SURVEY_ID, GClass0.smethod_0("JńɎ̓ыՐٜࡅ"), surveyMain_0.CLIENT_ID, 0); this.oSurveyAnswerDal.AddOne(surveyMain_0.SURVEY_ID, GClass0.smethod_0("Zśɇ͍уՆِݜࡋॅ"), surveyMain_0.PROJECT_ID, 0); string arg = surveyMain_0.END_TIME.ToString(); this.oSurveyAnswerDal.AddOne(surveyMain_0.SURVEY_ID, GClass0.smethod_0("CŚɜ͛щՒٕݏࡁॕെ์ཅ"), string.Format(GClass0.smethod_0("lĦȯͭѪի٨ܿࡂृਢ୨౯പแཀွᅫቨጾᑰᕱᙼ"), arg), 0); this.oSurveyAnswerDal.AddOne(surveyMain_0.SURVEY_ID, GClass0.smethod_0("\\śɟ͚юՓٖ݄ࡆॕੑెൌๅ"), string.Format(GClass0.smethod_0("lĦȯͭѪի٨ܿࡂृਢ୨౯പแཀွᅫቨጾᑰᕱᙼ"), arg), 0); string text = surveyMain_0.SURVEY_GUID.ToString(); if (surveyMain_0.VERSION_ID.IndexOf(GClass0.smethod_0("歠帍灉")) > -1) { text += GClass0.smethod_0("歠帍灉"); } else { text += "测试版"; } string string_ = EncryptTool.Encrypt(text, GClass0.smethod_0("EłɨͦѶպٲݵ")); this.oSurveyAnswerDal.AddOne(surveyMain_0.SURVEY_ID, GClass0.smethod_0("BŅɝ͘шՕٔ݃ࡇॆੂౚേ์ཆ၄"), string_, 0); TimeSpan timeSpan = surveyMain_0.END_TIME.Value - surveyMain_0.START_TIME.Value; this.oSurveyAnswerDal.AddOne(surveyMain_0.SURVEY_ID, GClass0.smethod_0("CŚɜ͛щՒٕ݊ࡇ॔ൊ๏ང"), ((int)timeSpan.TotalMinutes).ToString(), 0); }
public void Register(UserInfo user, string password) { LoginEntity loginEntity = new LoginEntity(); loginEntity.UserId = user.UserId; loginEntity.UserName = user.UserName; loginEntity.IsCanLogin = true; UserBaseEntity userBaseEntity = new UserBaseEntity(); userBaseEntity.UserId = user.UserId; userBaseEntity.RealName = user.RealName; userBaseEntity.Email = user.Email; userBaseEntity.CardType = user.IdCardType; userBaseEntity.CardNumber = user.IdCardNumber; userBaseEntity.Mobile = user.Mobile; UserBalanceEntity balanceEntity = new UserBalanceEntity(); balanceEntity.UserId = user.UserId; balanceEntity.Balance = 0; balanceEntity.Freeze = 0; try { using (ILHDBTran tran = BeginTran()) { UserManager manager = new UserManager(tran); password = EncryptTool.MD5(password); manager.AddLogin(loginEntity, password); manager.AddUserBase(userBaseEntity); manager.AddBalance(balanceEntity); tran.Commit(); } } catch (Exception ex) { string errMsg = "注册新用户失败 - 系统异常,请联系系统管理员!"; throw HandleException(LogCategory.Register, errMsg, ex); } }
public LoginEntity Authenticate(string userId, string password) { password = EncryptTool.MD5(password); Criteria cri = new Criteria(); cri.Add( Expression.And( Expression.Equal("UserId", userId) , Expression.Equal("Password", password) )); IList <UserPassowrdEntity> users = persistence.GetList <UserPassowrdEntity>(cri); if (users.Count > 0) { if (users[0].IsCanLogin) { return(users[0]); } throw new LoginException(LoginErrorType.UserCannotLogin); } throw new LoginException(LoginErrorType.UserIdOrPasswordError); }
static void UnzipDataAndSave(string dataFilePath, string dataVersion, string saveFile = "catchdata.json") { string text = ""; byte[] buffer = new byte[0x400]; StringBuilder builder = new StringBuilder(); using (Stream stream = new FileStream(dataFilePath, FileMode.Open)) { CryptoStream baseInputStream = new CryptoStream(stream, EncryptTool.GetDecryptorServiceProvider(dataVersion), CryptoStreamMode.Read); using (Stream stream3 = new GZipStream(baseInputStream, CompressionMode.Decompress)) { StreamReader reader = new StreamReader(stream3, Encoding.UTF8); FileStream fs = new FileStream(saveFile, FileMode.OpenOrCreate); stream3.CopyTo(fs); fs.Close(); stream3.Close(); } stream.Close(); } }
public FrameUserModel CheckLogin(string username, string password) { FrameUserModel userEntity = frameUserDAO.Query(t => t.F_Account == username).FirstOrDefault(); if (userEntity != null) { if (userEntity.F_EnabledMark == true) { //UserLogOnEntity userLogOnEntity = userLogOnApp.GetForm(userEntity.F_Id); string dbPassword = EncryptTool.MD5Encrypt64(password); if (dbPassword == userEntity.F_UserPassword) { //DateTime lastVisitTime = DateTime.Now; //int LogOnCount = (userLogOnEntity.F_LogOnCount).ToInt() + 1; //if (userLogOnEntity.F_LastVisitTime != null) //{ // userLogOnEntity.F_PreviousVisitTime = userLogOnEntity.F_LastVisitTime.ToDate(); //} //userLogOnEntity.F_LastVisitTime = lastVisitTime; //userLogOnEntity.F_LogOnCount = LogOnCount; //userLogOnApp.UpdateForm(userLogOnEntity); return(userEntity); } else { throw new Exception("密码不正确,请重新输入"); } } else { throw new Exception("账户被系统锁定,请联系管理员"); } } else { throw new Exception("账户不存在,请重新输入"); } }
public void SubmitForm(FrameUserDTO userEntity, string keyValue, string userId) { FrameUserModel frameUserModel = new FrameUserModel(); if (!string.IsNullOrEmpty(keyValue)) { frameUserModel = frameUserDAO.GetById(keyValue); frameUserModel.F_Account = userEntity.F_Account; //frameUserModel.F_UserPassword = userEntity.F_UserPassword; frameUserModel.F_RealName = userEntity.F_RealName; frameUserModel.F_NickName = userEntity.F_NickName; frameUserModel.F_HeadIcon = userEntity.F_HeadIcon; frameUserModel.F_Gender = userEntity.F_Gender; frameUserModel.F_Birthday = userEntity.F_Birthday; frameUserModel.F_MobilePhone = userEntity.F_MobilePhone; frameUserModel.F_Email = userEntity.F_Email; frameUserModel.F_WeChat = userEntity.F_WeChat; frameUserModel.F_ManagerId = userEntity.F_ManagerId; frameUserModel.F_SecurityLevel = userEntity.F_SecurityLevel; frameUserModel.F_Signature = userEntity.F_Signature; frameUserModel.F_OrganizeId = userEntity.F_OrganizeId; frameUserModel.F_DepartmentId = userEntity.F_DepartmentId; frameUserModel.F_RoleId = userEntity.F_RoleId; frameUserModel.F_DutyId = userEntity.F_DutyId; frameUserModel.F_IsAdministrator = userEntity.F_IsAdministrator; frameUserModel.F_SortCode = userEntity.F_SortCode; frameUserModel.F_EnabledMark = userEntity.F_EnabledMark; frameUserModel.F_Description = userEntity.F_Description; frameUserDAO.Update(frameUserModel, userId); } else { frameUserModel = AutoMapperHelper.MapTo <FrameUserModel>(userEntity); frameUserModel.F_UserPassword = EncryptTool.MD5Encrypt64(userEntity.F_UserPassword); frameUserDAO.Create(frameUserModel, userId); } }
public UserModel GetUserByUserNameAndPwd(string userName, string pwd) { pwd = EncryptTool.GetMd5By32(pwd); return(_userRepository.GetUserByUserNameAndPwd(userName, pwd)); }
/// <summary> /// Create user token /// </summary> /// <param name="user"></param> /// <returns></returns> public string CreateUserToken(User user) => EncryptTool.Encrypt($"{user.UserName}:{user.Password}", GlobalResources.SecretKey);
public ActionResult CheckLogin(string username, string password, string code) { //LogEntity logEntity = new LogEntity(); //logEntity.F_ModuleName = "系统登录"; //logEntity.F_Type = DbLogType.Login.ToString(); try { if (!username.Equals("bamaadmin1")) { var sessionCode = HttpContext.Session.GetString("session_verifycode"); if (sessionCode.IsEmpty() || EncryptTool.MD5Encrypt64(code.ToLower()) != sessionCode.ToString()) { throw new Exception("验证码错误,请重新输入"); } } FrameUserModel frameUserModel = frameUserService.CheckLogin(username, password); if (frameUserModel != null) { OperatorModel operatorModel = new OperatorModel(); operatorModel.UserId = frameUserModel.F_Id; operatorModel.UserCode = frameUserModel.F_Account; operatorModel.UserName = frameUserModel.F_RealName; operatorModel.CompanyId = frameUserModel.F_OrganizeId; operatorModel.DepartmentId = frameUserModel.F_DepartmentId; operatorModel.RoleId = frameUserModel.F_RoleId; //operatorModel.LoginIPAddress = Net.Ip; //operatorModel.LoginIPAddressName = Net.GetLocation(operatorModel.LoginIPAddress); operatorModel.LoginTime = DateTime.Now; operatorModel.LoginToken = EncryptTool.DESEncrypt(Guid.NewGuid().ToString()); if (frameUserModel.F_Account == "bamaadmin") { operatorModel.IsSystem = true; } else { operatorModel.IsSystem = false; } //OperatorProvider.Provider.AddCurrent(operatorModel); HttpContext.Response.Cookies.Append("jxkbd20180822", EncryptTool.DESEncrypt(operatorModel.ToJson()), new Microsoft.AspNetCore.Http.CookieOptions { Expires = DateTime.Now.AddMinutes(60 * 10) }); //logEntity.F_Account = userEntity.F_Account; //logEntity.F_NickName = userEntity.F_RealName; //logEntity.F_Result = true; //logEntity.F_Description = "登录成功"; //new LogApp().WriteDbLog(logEntity); } return(Content(new AjaxResult { state = ResultType.success.ToString(), message = "登录成功。" }.ToJson())); } catch (Exception ex) { //logEntity.F_Account = username; //logEntity.F_NickName = username; //logEntity.F_Result = false; //logEntity.F_Description = "登录失败," + ex.Message; //new LogApp().WriteDbLog(logEntity); return(Content(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }.ToJson())); } //return Content(new { state = "success", message = "登录成功。" }.ToJson()); }
/// <summary> /// Decrypt packet /// </summary> /// <param name="encryptedString"></param> /// <returns></returns> protected Packet DecryptPacket(string encryptedString) { var decrypted = EncryptTool.Decrypt(encryptedString, GlobalResources.SecretKey); return(decrypted.Deserialize <Packet>()); }
public static string CreateTKForUserName(string username, string dynamicpassword) { return(System.Web.HttpUtility.UrlEncode(EncryptTool.Encrypt(string.Concat("WeChatUserName:"******":", dynamicpassword), MyCustomMessageHandler.SecretGuid, false))); }
/// <summary> /// 新建验证码 /// </summary> /// <returns></returns> public byte[] GetVerifyCode() { int codeW = 80; int codeH = 30; int fontSize = 16; string chkCode = string.Empty; //颜色列表,用于验证码、噪线、噪点 Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue }; //字体列表,用于验证码 string[] font = { "Times New Roman" }; //验证码的字符集,去掉了一些容易混淆的字符 char[] character = { '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'd', 'e', 'f', 'h', 'k', 'm', 'n', 'r', 'x', 'y', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' }; Random rnd = new Random(); //生成验证码字符串 for (int i = 0; i < 4; i++) { chkCode += character[rnd.Next(character.Length)]; } //写入Session、验证码加密 HttpContext.Session.SetString("session_verifycode", EncryptTool.MD5Encrypt64(chkCode.ToLower())); //创建画布 Bitmap bmp = new Bitmap(codeW, codeH); Graphics g = Graphics.FromImage(bmp); g.Clear(Color.White); //画噪线 for (int i = 0; i < 3; i++) { int x1 = rnd.Next(codeW); int y1 = rnd.Next(codeH); int x2 = rnd.Next(codeW); int y2 = rnd.Next(codeH); Color clr = color[rnd.Next(color.Length)]; g.DrawLine(new Pen(clr), x1, y1, x2, y2); } //画验证码字符串 for (int i = 0; i < chkCode.Length; i++) { string fnt = font[rnd.Next(font.Length)]; Font ft = new Font(fnt, fontSize); Color clr = color[rnd.Next(color.Length)]; g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 18, (float)0); } //将验证码图片写入内存流,并将其以 "image/Png" 格式输出 MemoryStream ms = new MemoryStream(); try { bmp.Save(ms, ImageFormat.Png); return(ms.ToArray()); } catch (Exception) { return(null); } finally { g.Dispose(); bmp.Dispose(); } }