Model
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Linq; 5 using System.Security.Cryptography; 6 using System.Text; 7 using System.Threading.Tasks; 8 using System.Web; 9 10 namespace VerificationCode.Code 11 { 12 public class VerificationCodeAESHelp 13 { 14 /// <summary> 15 /// Key123Ace#321Key 16 /// </summary> 17 private static readonly string _AESKEY = "qwertyuiopasdfghjklzxcvbnm123456"; 18 19 /// <summary> 20 /// slide 21 /// </summary> 22 public const string _SlideCode = "slidecode."; 23 24 /// <summary> 25 ///验证码cookie 26 /// </summary> 27 public const string _YZM = "_YZM."; 28 29 30 private HttpContextBase _httpContextAccessor; 31 32 public VerificationCodeAESHelp(HttpContextBase httpContextAccessor) 33 { 34 this._httpContextAccessor = httpContextAccessor; 35 } 36 37 38 /// <summary> 39 /// AES加密返回base64字符串 40 /// </summary> 41 public string AES_Encrypt_Return_Base64String(string str) 42 { 43 string base64Str = AESEncrypt(str, _AESKEY); 44 45 return base64Str; 46 } 47 48 49 /// <summary> 50 /// AES解密返回string 51 /// </summary> 52 public string AES_Decrypt_Return_String(string str) 53 { 54 return AESDecrypt(str, _AESKEY); 55 } 56 57 58 59 #region AES 60 61 private static string SubString(string sourceStr, int startIndex, int length) 62 { 63 string str; 64 if (string.IsNullOrEmpty(sourceStr)) 65 { 66 str = ""; 67 } 68 else 69 { 70 str = (sourceStr.Length < startIndex + length ? sourceStr.Substring(startIndex) : sourceStr.Substring(startIndex, length)); 71 } 72 return str; 73 } 74 75 76 private static byte[] _aeskeys = new byte[] { 18, 52, 86, 120, 144, 171, 205, 239, 18, 52, 86, 120, 144, 171, 205, 239 }; 77 /// <summary> 78 /// 加密 79 /// </summary> 80 /// <param name="input"></param> 81 /// <param name="key"></param> 82 /// <returns></returns> 83 private static string AESEncrypt(string encryptStr, string encryptKey) 84 { 85 86 string base64String; 87 if (!string.IsNullOrWhiteSpace(encryptStr)) 88 { 89 encryptKey = SubString(encryptKey, 0, 32); 90 encryptKey = encryptKey.PadRight(32, ' '); 91 SymmetricAlgorithm bytes = Rijndael.Create(); 92 byte[] numArray = Encoding.UTF8.GetBytes(encryptStr); 93 bytes.Key = Encoding.UTF8.GetBytes(encryptKey); 94 bytes.IV = _aeskeys; 95 byte[] array = null; 96 MemoryStream memoryStream = new MemoryStream(); 97 try 98 { 99 CryptoStream cryptoStream = new CryptoStream(memoryStream, bytes.CreateEncryptor(), CryptoStreamMode.Write); 100 try 101 { 102 cryptoStream.Write(numArray, 0, numArray.Length); 103 cryptoStream.FlushFinalBlock(); 104 array = memoryStream.ToArray(); 105 cryptoStream.Close(); 106 memoryStream.Close(); 107 } 108 finally 109 { 110 if (cryptoStream != null) 111 { 112 ((IDisposable)cryptoStream).Dispose(); 113 } 114 } 115 } 116 finally 117 { 118 if (memoryStream != null) 119 { 120 ((IDisposable)memoryStream).Dispose(); 121 } 122 } 123 base64String = Convert.ToBase64String(array); 124 } 125 else 126 { 127 base64String = string.Empty; 128 } 129 return base64String; 130 131 } 132 133 134 135 /// <summary> 136 /// 解密 137 /// </summary> 138 /// <param name="input"></param> 139 /// <param name="key"></param> 140 /// <returns></returns> 141 private static string AESDecrypt(string decryptStr, string decryptKey) 142 { 143 144 string empty; 145 if (!string.IsNullOrWhiteSpace(decryptStr)) 146 { 147 decryptKey = SubString(decryptKey, 0, 32); 148 decryptKey = decryptKey.PadRight(32, ' '); 149 byte[] numArray = Convert.FromBase64String(decryptStr); 150 SymmetricAlgorithm bytes = Rijndael.Create(); 151 bytes.Key = Encoding.UTF8.GetBytes(decryptKey); 152 bytes.IV = _aeskeys; 153 byte[] numArray1 = new byte[numArray.Length]; 154 MemoryStream memoryStream = new MemoryStream(numArray); 155 try 156 { 157 CryptoStream cryptoStream = new CryptoStream(memoryStream, bytes.CreateDecryptor(), CryptoStreamMode.Read); 158 try 159 { 160 cryptoStream.Read(numArray1, 0, numArray1.Length); 161 cryptoStream.Close(); 162 memoryStream.Close(); 163 } 164 finally 165 { 166 if (cryptoStream != null) 167 { 168 ((IDisposable)cryptoStream).Dispose(); 169 } 170 } 171 } 172 finally 173 { 174 if (memoryStream != null) 175 { 176 ((IDisposable)memoryStream).Dispose(); 177 } 178 } 179 empty = Encoding.UTF8.GetString(numArray1).Replace("\0", ""); 180 } 181 else 182 { 183 empty = string.Empty; 184 } 185 return empty; 186 187 } 188 189 #endregion 190 191 192 #region Cookie 193 194 /// <summary> 195 /// 196 /// </summary> 197 /// <param name="key"></param> 198 /// <param name="value"></param> 199 /// <param name="minute"></param> 200 public void SetCookie(HttpContextBase httpContext,string key, string value, int minute) 201 { 202 203 HttpCookie cookie = new HttpCookie(key); 204 cookie.Value = value; 205 cookie.Expires = DateTime.Now.AddDays(minute); 206 httpContext.Response.Cookies.Add(cookie); 207 } 208 209 210 211 /// <summary> 212 /// 213 /// </summary> 214 /// <param name="key"></param> 215 /// <returns>string</returns> 216 public string GetCookie(HttpContextBase httpContext,string key) 217 { 218 string _cookie = httpContext.Request.Cookies[key].Value; 219 return _cookie; 220 } 221 222 223 224 #endregion 225 } 226 }
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 using System; 2 using System.Collections.Generic; 3 using System.Drawing; 4 using System.Drawing.Imaging; 5 using System.IO; 6 using System.Linq; 7 using System.Threading.Tasks; 8 9 namespace VerificationCode.Code 10 { 11 public class VerificationCodeImage 12 { 13 14 /// <summary> 15 /// 随机汉字 16 /// </summary> 17 /// <param name="number"></param> 18 /// <returns></returns> 19 private static string RandomHanZi(int number) 20 { 21 var str = "奉利民邱喜威刘鹏李明洋李国霜"; 22 char[] str_char_arrary = str.ToArray(); 23 Random rand = new Random(); 24 HashSet<string> hs = new HashSet<string>(); 25 bool randomBool = true; 26 while (randomBool) 27 { 28 if (hs.Count == number) 29 break; 30 int rand_number = rand.Next(str_char_arrary.Length); 31 hs.Add(str_char_arrary[rand_number].ToString()); 32 } 33 string code = string.Join("", hs); 34 return code; 35 } 36 37 /// <summary> 38 /// </summary> 39 /// <param name="numbers">生成位数(默认5位)</param> 40 /// <param name="_height">图片高度</param> 41 /// <param name="_width">图片宽度</param> 42 public static Task<VerificationCodeModel> CreateHanZi(int numbers = 5, int _height = 200, int _width = 200) 43 { 44 var imageModel = new VerificationCodeModel(); 45 if (imageModel.point_X_Y == null) 46 { 47 imageModel.point_X_Y = new List<Point_X_Y>(); 48 } 49 string code = RandomHanZi(numbers); 50 Bitmap Img = null; 51 Graphics g = null; 52 MemoryStream ms = null; 53 Random random = new Random(); 54 55 Color[] color_Array = { Color.Black, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple }; 56 string[] fonts = { "lnk Free", "Segoe Print", "Comic Sans MS", "MV Boli", "华文行楷" }; 57 //string _base = Environment.CurrentDirectory + "\\wwwroot\\verificationcodeImage\\"; 58 string _base = System.Web.HttpContext.Current.Server.MapPath("~/CallWebLog/"); 59 if (!System.IO.Directory.Exists(_base)) 60 { 61 System.IO.Directory.CreateDirectory(_base); 62 } 63 var _file_List = System.IO.Directory.GetFiles(_base); 64 int imageCount = _file_List.Length; 65 if (imageCount == 0) 66 throw new Exception("image not Null"); 67 68 int imageRandom = random.Next(1, (imageCount + 1)); 69 string _random_file_image = _file_List[imageRandom - 1]; 70 var imageStream = Image.FromFile(_random_file_image); 71 72 Img = new Bitmap(imageStream, _width, _height); 73 imageStream.Dispose(); 74 g = Graphics.FromImage(Img); 75 Color[] penColor = { Color.LightGray, Color.Green, Color.Blue }; 76 int code_length = code.Length; 77 for (int i = 0; i < code_length; i++) 78 { 79 int cindex = random.Next(color_Array.Length); 80 int findex = random.Next(fonts.Length); 81 Font f = new Font(fonts[findex], 15, FontStyle.Bold); 82 Brush b = new SolidBrush(color_Array[cindex]); 83 int _y = random.Next(_height); 84 if (_y > (_height - 30)) 85 _y = _y - 60; 86 87 int _x = _width / (i + 1); 88 if ((_width - _x) < 50) 89 { 90 _x = _width - 60; 91 } 92 string word = code.Substring(i, 1); 93 if (imageModel.point_X_Y.Count < 3) 94 { 95 imageModel.point_X_Y.Add(new Point_X_Y() 96 { 97 Word = word, 98 _X = _x, 99 _Y = _y, 100 Sort = i 101 }); 102 } 103 g.DrawString(word, f, b, _x, _y); 104 } 105 ms = new MemoryStream(); 106 Img.Save(ms, ImageFormat.Jpeg); 107 g.Dispose(); 108 Img.Dispose(); 109 ms.Dispose(); 110 imageModel.ImageBase64Str = "data:image/jpg;base64," + Convert.ToBase64String(ms.GetBuffer()); 111 return Task.FromResult(imageModel); 112 } 113 114 115 116 } 117 118 119 public class Point_X_Y 120 { 121 public int _X { get; set; } 122 123 public int _Y { get; set; } 124 125 public int Sort { get; set; } 126 127 public string Word { get; set; } 128 129 } 130 131 /// <summary> 132 /// 滑动校验 133 /// </summary> 134 public class SlideVerifyCodeModel 135 { 136 public bool SlideCode { get; set; } 137 138 public DateTime timestamp 139 { 140 get { return DateTime.Now; } 141 set 142 { 143 144 } 145 } 146 } 147 148 149 public class VerificationCodeModel 150 { 151 public string ImageBase64Str { get; set; } 152 153 public List<Point_X_Y> point_X_Y { get; set; } 154 155 } 156 157 }
Controllers
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 using System; 2 using System.Collections.Generic; 3 using System.Diagnostics; 4 using System.Linq; 5 using System.Threading.Tasks; 6 using System.Web; 7 using System.Web.Mvc; 8 using VerificationCode.Code; 9 10 namespace Zeujs.Controllers 11 { 12 public class DefaultController : Controller 13 { 14 15 private VerificationCodeAESHelp _verificationCodeAESHelp; 16 17 /// <summary> 18 /// 构造函数 19 /// </summary> 20 public DefaultController() 21 { 22 this._verificationCodeAESHelp = new VerificationCodeAESHelp(HttpContext); 23 } 24 25 public ActionResult GetVerificationCodeImage() 26 { 27 var model = VerificationCode.Code.VerificationCodeImage.CreateHanZi(); 28 VerificationCodeAESHelp help = new VerificationCodeAESHelp(HttpContext); 29 var json_Model = Newtonsoft.Json.JsonConvert.SerializeObject(model.Result.point_X_Y); 30 string pointBase64str = help.AES_Encrypt_Return_Base64String(json_Model); 31 help.SetCookie(HttpContext, VerificationCodeAESHelp._YZM, pointBase64str, 5); 32 string msg = "请根据顺序点击【" + string.Join("", model.Result.point_X_Y.Select(x => x.Word).ToList()) + "】"; 33 return Json(new { result = model.Result.ImageBase64Str, msg = msg }); 34 } 35 36 public ActionResult CheckCode(string code) 37 { 38 try 39 { 40 if (this._verificationCodeAESHelp == null) 41 { 42 this._verificationCodeAESHelp = new VerificationCodeAESHelp(HttpContext); 43 } 44 var pointList = new List<Point_X_Y>(); 45 try 46 { 47 pointList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Point_X_Y>>(code); 48 } 49 catch (Exception) 50 { 51 return Json(new { msg = "验证失败!", status = "error" }); 52 } 53 54 if (pointList.Count != 3) 55 return Json(new { msg = "验证失败!", status = "error" }); 56 57 var _cookie = this._verificationCodeAESHelp.GetCookie(HttpContext, VerificationCodeAESHelp._YZM); 58 59 if (string.IsNullOrEmpty(_cookie)) 60 return Json(new { msg = "验证失败!", status = "error" }); 61 62 string _str = this._verificationCodeAESHelp.AES_Decrypt_Return_String(_cookie); 63 64 var _cookiesPointList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Point_X_Y>>(_str); 65 _cookiesPointList = _cookiesPointList.OrderBy(x => x.Sort).ToList(); 66 int i = 0; 67 foreach (var item in pointList.AsParallel()) 68 { 69 int _x = _cookiesPointList[i]._X - item._X; 70 int _y = _cookiesPointList[i]._Y - item._Y; 71 _x = Math.Abs(_x); 72 _y = Math.Abs(_y); 73 if (_x > 25 || _y > 25) 74 { 75 return Json(new { msg = "验证失败!", status = "error" }); 76 } 77 i++; 78 } 79 80 SlideVerifyCode(true); 81 82 } 83 catch (Exception) 84 { 85 return Json(new { msg = "验证失败!", status = "error" }); 86 } 87 return Json(new { msg = "验证通过!", status = "ok" }); 88 } 89 90 91 92 [HttpPost] 93 public ActionResult Logins(string userName, string passWord) 94 { 95 Tuple<bool, string> tuple = VerifyValiate(); 96 if (!tuple.Item1) 97 { 98 return Json(new { msg = tuple.Item2, status = "error" }); 99 } 100 if (userName == "admin" && passWord == "admin") 101 { 102 return Json(new { msg = "登陆成功!", status = "ok" }); 103 } 104 else 105 { 106 return Json(new { msg = "账号密码错误!", status = "error" }); 107 } 108 } 109 110 public Tuple<bool, string> VerifyValiate() 111 { 112 var _cookie = this._verificationCodeAESHelp.GetCookie(HttpContext, VerificationCodeAESHelp._SlideCode); 113 if (string.IsNullOrEmpty(_cookie)) 114 { 115 SlideVerifyCode(); 116 return new Tuple<bool, string>(false, "请拖动滑块"); 117 } 118 string _str = this._verificationCodeAESHelp.AES_Decrypt_Return_String(_cookie); 119 var sildeCodeModel = Newtonsoft.Json.JsonConvert.DeserializeObject<SlideVerifyCodeModel>(_str); 120 if (!sildeCodeModel.SlideCode) 121 { 122 return new Tuple<bool, string>(false, "请拖动滑块后点击汉字"); 123 } 124 var _NowTime = DateTime.Now; 125 var _time = sildeCodeModel.timestamp; 126 var number = (_NowTime - _time).Minutes; 127 if (number > 5) 128 { 129 SlideVerifyCode(); 130 return new Tuple<bool, string>(false, "滑块验证码过期"); 131 } 132 return new Tuple<bool, string>(true, "成功"); 133 } 134 135 136 private void SlideVerifyCode(bool _bool = false) 137 { 138 var json = Newtonsoft.Json.JsonConvert.SerializeObject(new SlideVerifyCodeModel() { SlideCode = _bool, timestamp = DateTime.Now }); 139 string base64Str = this._verificationCodeAESHelp.AES_Encrypt_Return_Base64String(json); 140 this._verificationCodeAESHelp.SetCookie(HttpContext, VerificationCodeAESHelp._SlideCode, base64Str, 10); 141 142 } 143 144 145 146 } 147 }
View
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 @{ 2 ViewData["Title"] = "Home Page"; 3 Layout = null; 4 } 5 6 <!DOCTYPE html> 7 <html> 8 <head> 9 <meta charset="utf-8" /> 10 <title>登录 </title> 11 12 <link href="~/wwwroot/css/style.css" rel="stylesheet" /> 13 <link href="~/wwwroot/css/slide-unlock.css" rel="stylesheet" /> 14 15 <style> 16 body { 17 height: 100%; 18 background: #16a085; 19 overflow: hidden; 20 } 21 22 canvas { 23 z-index: -1; 24 position: absolute; 25 } 26 </style> 27 <script src="~/wwwroot/js/jquery1.11.1.js"></script> 28 29 <script src="/wwwroot/js/Particleground.js" tppabs="js/Particleground.js"></script> 30 <script src="~/wwwroot/js/slide.js"></script> 31 32 <script> 33 34 $(document).ready(function () { 35 36 $(".submit_btn").click(function () { 37 if ($("#labelTip").html() == "拖动滑块验证") 38 { 39 alert("请拖动滑块验证!"); 40 return; 41 } 42 $.ajax({ 43 url: "@Url.Action("Logins", "default")", 44 type: "post", 45 data: { 46 "userName": $("#userName").val(), 47 "passWord": $("#passWord").val() 48 }, 49 success: function (d) { 50 if (d.status != "ok") { 51 alert(d.msg); 52 Slider_init(); 53 } else { 54 alert(d.msg); 55 window.location.href = "@Url.Action("index")"; 56 } 57 } 58 }) 59 60 61 }) 62 63 64 //粒子背景特效 65 $('body').particleground({ 66 dotColor: '#5cbdaa', 67 lineColor: '#5cbdaa' 68 }); 69 70 Slider_init(); 71 }); 72 73 74 function Slider_init() { 75 var slider = new SliderUnlock("#slider", { 76 successLabelTip: "验证成功" 77 }, function () { 78 79 huadongCode(); 80 }); 81 slider.init(); 82 } 83 84 85 86 function huadongCode() { 87 num = 1; 88 checkCode = []; 89 $.ajax({ 90 type: "Post", 91 url: "@Url.Action("GetVerificationCodeImage", "Default")", 92 dataType: "json", 93 beforeSend: function (XMLHttpRequest) { 94 console.log(this); 95 96 }, 97 success: function (data) { 98 var html = "<div id=\"imagediv\" style='position: absolute;left:10px; top:30px;background: #fff;z-index:300'><img src=" + data.result + " alt=\"看不清?点击更换\" id=\"image\"/></div>"; 99 html += "<div id='divrefresh' style='width:20px;height:20px;position:absolute;cursor: pointer;margin-left: 90%;'> <img src=\"/wwwroot/images/shaxin.jpg\" /> </div>"; 100 $("#huadongImage").css("display", "block").html(html); 101 $("#labelTip").html(data.msg); 102 imageClick(); 103 divrefreshClick(); 104 105 } 106 }) 107 108 @* $.ajax({ 109 "url": "@Url.Action("GetVerificationCodeImage","Default")", 110 "type": "get", 111 "success": function (data) { 112 var html = "<div id=\"imagediv\" style='position: absolute;left:10px; top:30px;background: #fff;z-index:300'><img src=" + data.result + " alt=\"看不清?点击更换\" id=\"image\"/></div>"; 113 html += "<div id='divrefresh' style='width:20px;height:20px;position:absolute;cursor: pointer;margin-left: 90%;'> <img src=\"/images/shaxin.jpg\" /> </div>"; 114 $("#huadongImage").css("display", "block").html(html); 115 $("#labelTip").html(data.msg); 116 imageClick(); 117 divrefreshClick(); 118 }, 119 "complete": function (XMLHttpRequest, status) { 120 if (status == 'timeout') { 121 122 } 123 alert("1"); 124 } 125 })*@ 126 } 127 128 129 function divrefreshClick() { 130 $("#divrefresh").click(function () { 131 huadongCode(); 132 num = 1; 133 checkCode = []; 134 }) 135 } 136 137 138 var num = 1; 139 var checkCode = []; 140 function createPoint(pos) { 141 if (num == 3) { 142 PostcheckCode(); 143 } 144 145 $("#imagediv").append('<div class="point-area" οnclick="pointClick(this)" style="background-color:#539ffe;color:#fff;z-index:9999;width:25px;height:25px;text-align:center;line-height:25px;border-radius: 20%;position:absolute;border:2px solid white;top:' + parseInt(pos.y - 10) + 'px;left:' + parseInt(pos.x - 10) + 'px;">' + num + '</div>'); 146 ++num; 147 } 148 149 150 151 function PostcheckCode() { 152 $.ajax({ 153 "url": "/Default/CheckCode", 154 "type": "post", 155 "data": { 156 "code": JSON.stringify(checkCode) 157 }, 158 "success": function (d) { 159 if (d.status == "ok") { 160 $("#labelTip").html(d.msg); 161 $("#huadongImage").hide(); 162 } else { 163 huadongCode(); 164 } 165 }, 166 "error": function (error) { 167 168 } 169 }) 170 171 } 172 173 174 175 function pointClick(obj) { 176 num = 1; 177 checkCode = []; 178 $(obj).parent().find('.point-area').remove(); 179 } 180 181 182 function getMousePos(obj, event) { 183 var e = event || window.event; 184 var x = e.clientX - ($(obj).offset().left - $(window).scrollLeft()); 185 var y = e.clientY - ($(obj).offset().top - $(window).scrollTop()); 186 checkCode.push({ "_X": parseInt(x), "_Y": parseInt(y) }); 187 return { 'x': parseInt(x), 'y': parseInt(y) }; 188 } 189 190 function imageClick() { 191 $("#imagediv").click(function () { 192 var _this = $(this); 193 var pos = getMousePos(_this); 194 createPoint(pos); 195 }) 196 197 } 198 </script> 199 </head> 200 <body> 201 <dl class="admin_login"> 202 <dt> 203 <strong>登录</strong> 204 <em></em> 205 </dt> 206 <dd class="user_icon"> 207 <input type="text" id="userName" placeholder="账号" class="login_txtbx" name="userName" data-val="true" data-val-required="賬號不能为空" /> 208 <span class="field-validation-valid" data-valmsg-for="userName" data-valmsg-replace="true" style="color: #ff0000"></span> 209 </dd> 210 <dd class="pwd_icon"> 211 <input type="password" id="passWord" placeholder="密码" class="login_txtbx" /> 212 </dd> 213 <dd class="val_icon"> 214 <div id="slider"> 215 <div id="slider_bg"></div> 216 <span id="label">>></span> 217 <span id="labelTip">拖动滑块验证</span> 218 </div> 219 220 <div id="huadongImage" style="width: 300px; border: 1px solid #ccc; height: 250px; z-index: 200; display: none; position: absolute; background-color: white; top: 40px;"> 221 </div> 222 </dd> 223 <dd> 224 <input type="submit" value="立即登陆" class="submit_btn" /> 225 </dd> 226 <dd></dd> 227 </dl> 228 </body> 229 </html>
样式请去http://www.bootcss.com/下载