Model

 using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web; namespace VerificationCode.Code
{
public class VerificationCodeAESHelp
{
/// <summary>
/// Key123Ace#321Key
/// </summary>
private static readonly string _AESKEY = "qwertyuiopasdfghjklzxcvbnm123456"; /// <summary>
/// slide
/// </summary>
public const string _SlideCode = "slidecode."; /// <summary>
///验证码cookie
/// </summary>
public const string _YZM = "_YZM."; private HttpContextBase _httpContextAccessor; public VerificationCodeAESHelp(HttpContextBase httpContextAccessor)
{
this._httpContextAccessor = httpContextAccessor;
} /// <summary>
/// AES加密返回base64字符串
/// </summary>
public string AES_Encrypt_Return_Base64String(string str)
{
string base64Str = AESEncrypt(str, _AESKEY); return base64Str;
} /// <summary>
/// AES解密返回string
/// </summary>
public string AES_Decrypt_Return_String(string str)
{
return AESDecrypt(str, _AESKEY);
} #region AES private static string SubString(string sourceStr, int startIndex, int length)
{
string str;
if (string.IsNullOrEmpty(sourceStr))
{
str = "";
}
else
{
str = (sourceStr.Length < startIndex + length ? sourceStr.Substring(startIndex) : sourceStr.Substring(startIndex, length));
}
return str;
} private static byte[] _aeskeys = new byte[] { , , , , , , , , , , , , , , , };
/// <summary>
/// 加密
/// </summary>
/// <param name="input"></param>
/// <param name="key"></param>
/// <returns></returns>
private static string AESEncrypt(string encryptStr, string encryptKey)
{ string base64String;
if (!string.IsNullOrWhiteSpace(encryptStr))
{
encryptKey = SubString(encryptKey, , );
encryptKey = encryptKey.PadRight(, ' ');
SymmetricAlgorithm bytes = Rijndael.Create();
byte[] numArray = Encoding.UTF8.GetBytes(encryptStr);
bytes.Key = Encoding.UTF8.GetBytes(encryptKey);
bytes.IV = _aeskeys;
byte[] array = null;
MemoryStream memoryStream = new MemoryStream();
try
{
CryptoStream cryptoStream = new CryptoStream(memoryStream, bytes.CreateEncryptor(), CryptoStreamMode.Write);
try
{
cryptoStream.Write(numArray, , numArray.Length);
cryptoStream.FlushFinalBlock();
array = memoryStream.ToArray();
cryptoStream.Close();
memoryStream.Close();
}
finally
{
if (cryptoStream != null)
{
((IDisposable)cryptoStream).Dispose();
}
}
}
finally
{
if (memoryStream != null)
{
((IDisposable)memoryStream).Dispose();
}
}
base64String = Convert.ToBase64String(array);
}
else
{
base64String = string.Empty;
}
return base64String; } /// <summary>
/// 解密
/// </summary>
/// <param name="input"></param>
/// <param name="key"></param>
/// <returns></returns>
private static string AESDecrypt(string decryptStr, string decryptKey)
{ string empty;
if (!string.IsNullOrWhiteSpace(decryptStr))
{
decryptKey = SubString(decryptKey, , );
decryptKey = decryptKey.PadRight(, ' ');
byte[] numArray = Convert.FromBase64String(decryptStr);
SymmetricAlgorithm bytes = Rijndael.Create();
bytes.Key = Encoding.UTF8.GetBytes(decryptKey);
bytes.IV = _aeskeys;
byte[] numArray1 = new byte[numArray.Length];
MemoryStream memoryStream = new MemoryStream(numArray);
try
{
CryptoStream cryptoStream = new CryptoStream(memoryStream, bytes.CreateDecryptor(), CryptoStreamMode.Read);
try
{
cryptoStream.Read(numArray1, , numArray1.Length);
cryptoStream.Close();
memoryStream.Close();
}
finally
{
if (cryptoStream != null)
{
((IDisposable)cryptoStream).Dispose();
}
}
}
finally
{
if (memoryStream != null)
{
((IDisposable)memoryStream).Dispose();
}
}
empty = Encoding.UTF8.GetString(numArray1).Replace("\0", "");
}
else
{
empty = string.Empty;
}
return empty; } #endregion #region Cookie /// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="minute"></param>
public void SetCookie(HttpContextBase httpContext,string key, string value, int minute)
{ HttpCookie cookie = new HttpCookie(key);
cookie.Value = value;
cookie.Expires = DateTime.Now.AddDays(minute);
httpContext.Response.Cookies.Add(cookie);
} /// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <returns>string</returns>
public string GetCookie(HttpContextBase httpContext,string key)
{
string _cookie = httpContext.Request.Cookies[key].Value;
return _cookie;
} #endregion
}
}

VerificationCodeAESHelp

 using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Threading.Tasks; namespace VerificationCode.Code
{
public class VerificationCodeImage
{ /// <summary>
/// 随机汉字
/// </summary>
/// <param name="number"></param>
/// <returns></returns>
private static string RandomHanZi(int number)
{
var str = "奉利民邱喜威刘鹏李明洋李国霜";
char[] str_char_arrary = str.ToArray();
Random rand = new Random();
HashSet<string> hs = new HashSet<string>();
bool randomBool = true;
while (randomBool)
{
if (hs.Count == number)
break;
int rand_number = rand.Next(str_char_arrary.Length);
hs.Add(str_char_arrary[rand_number].ToString());
}
string code = string.Join("", hs);
return code;
} /// <summary>
/// </summary>
/// <param name="numbers">生成位数(默认5位)</param>
/// <param name="_height">图片高度</param>
/// <param name="_width">图片宽度</param>
public static Task<VerificationCodeModel> CreateHanZi(int numbers = , int _height = , int _width = )
{
var imageModel = new VerificationCodeModel();
if (imageModel.point_X_Y == null)
{
imageModel.point_X_Y = new List<Point_X_Y>();
}
string code = RandomHanZi(numbers);
Bitmap Img = null;
Graphics g = null;
MemoryStream ms = null;
Random random = new Random(); Color[] color_Array = { Color.Black, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
string[] fonts = { "lnk Free", "Segoe Print", "Comic Sans MS", "MV Boli", "华文行楷" };
//string _base = Environment.CurrentDirectory + "\\wwwroot\\verificationcodeImage\\";
string _base = System.Web.HttpContext.Current.Server.MapPath("~/CallWebLog/");
if (!System.IO.Directory.Exists(_base))
{
System.IO.Directory.CreateDirectory(_base);
}
var _file_List = System.IO.Directory.GetFiles(_base);
int imageCount = _file_List.Length;
if (imageCount == )
throw new Exception("image not Null"); int imageRandom = random.Next(, (imageCount + ));
string _random_file_image = _file_List[imageRandom - ];
var imageStream = Image.FromFile(_random_file_image); Img = new Bitmap(imageStream, _width, _height);
imageStream.Dispose();
g = Graphics.FromImage(Img);
Color[] penColor = { Color.LightGray, Color.Green, Color.Blue };
int code_length = code.Length;
for (int i = ; i < code_length; i++)
{
int cindex = random.Next(color_Array.Length);
int findex = random.Next(fonts.Length);
Font f = new Font(fonts[findex], , FontStyle.Bold);
Brush b = new SolidBrush(color_Array[cindex]);
int _y = random.Next(_height);
if (_y > (_height - ))
_y = _y - ; int _x = _width / (i + );
if ((_width - _x) < )
{
_x = _width - ;
}
string word = code.Substring(i, );
if (imageModel.point_X_Y.Count < )
{
imageModel.point_X_Y.Add(new Point_X_Y()
{
Word = word,
_X = _x,
_Y = _y,
Sort = i
});
}
g.DrawString(word, f, b, _x, _y);
}
ms = new MemoryStream();
Img.Save(ms, ImageFormat.Jpeg);
g.Dispose();
Img.Dispose();
ms.Dispose();
imageModel.ImageBase64Str = "data:image/jpg;base64," + Convert.ToBase64String(ms.GetBuffer());
return Task.FromResult(imageModel);
} } public class Point_X_Y
{
public int _X { get; set; } public int _Y { get; set; } public int Sort { get; set; } public string Word { get; set; } } /// <summary>
/// 滑动校验
/// </summary>
public class SlideVerifyCodeModel
{
public bool SlideCode { get; set; } public DateTime timestamp
{
get { return DateTime.Now; }
set
{ }
}
} public class VerificationCodeModel
{
public string ImageBase64Str { get; set; } public List<Point_X_Y> point_X_Y { get; set; } } }

VerificationCodeImage

Controllers

 using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using VerificationCode.Code; namespace Zeujs.Controllers
{
public class DefaultController : Controller
{ private VerificationCodeAESHelp _verificationCodeAESHelp; /// <summary>
/// 构造函数
/// </summary>
public DefaultController()
{
this._verificationCodeAESHelp = new VerificationCodeAESHelp(HttpContext);
} public ActionResult GetVerificationCodeImage()
{
var model = VerificationCode.Code.VerificationCodeImage.CreateHanZi();
VerificationCodeAESHelp help = new VerificationCodeAESHelp(HttpContext);
var json_Model = Newtonsoft.Json.JsonConvert.SerializeObject(model.Result.point_X_Y);
string pointBase64str = help.AES_Encrypt_Return_Base64String(json_Model);
help.SetCookie(HttpContext, VerificationCodeAESHelp._YZM, pointBase64str, );
string msg = "请根据顺序点击【" + string.Join("", model.Result.point_X_Y.Select(x => x.Word).ToList()) + "】";
return Json(new { result = model.Result.ImageBase64Str, msg = msg });
} public ActionResult CheckCode(string code)
{
try
{
if (this._verificationCodeAESHelp == null)
{
this._verificationCodeAESHelp = new VerificationCodeAESHelp(HttpContext);
}
var pointList = new List<Point_X_Y>();
try
{
pointList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Point_X_Y>>(code);
}
catch (Exception)
{
return Json(new { msg = "验证失败!", status = "error" });
} if (pointList.Count != )
return Json(new { msg = "验证失败!", status = "error" }); var _cookie = this._verificationCodeAESHelp.GetCookie(HttpContext, VerificationCodeAESHelp._YZM); if (string.IsNullOrEmpty(_cookie))
return Json(new { msg = "验证失败!", status = "error" }); string _str = this._verificationCodeAESHelp.AES_Decrypt_Return_String(_cookie); var _cookiesPointList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Point_X_Y>>(_str);
_cookiesPointList = _cookiesPointList.OrderBy(x => x.Sort).ToList();
int i = ;
foreach (var item in pointList.AsParallel())
{
int _x = _cookiesPointList[i]._X - item._X;
int _y = _cookiesPointList[i]._Y - item._Y;
_x = Math.Abs(_x);
_y = Math.Abs(_y);
if (_x > || _y > )
{
return Json(new { msg = "验证失败!", status = "error" });
}
i++;
} SlideVerifyCode(true); }
catch (Exception)
{
return Json(new { msg = "验证失败!", status = "error" });
}
return Json(new { msg = "验证通过!", status = "ok" });
} [HttpPost]
public ActionResult Logins(string userName, string passWord)
{
Tuple<bool, string> tuple = VerifyValiate();
if (!tuple.Item1)
{
return Json(new { msg = tuple.Item2, status = "error" });
}
if (userName == "admin" && passWord == "admin")
{
return Json(new { msg = "登陆成功!", status = "ok" });
}
else
{
return Json(new { msg = "账号密码错误!", status = "error" });
}
} public Tuple<bool, string> VerifyValiate()
{
var _cookie = this._verificationCodeAESHelp.GetCookie(HttpContext, VerificationCodeAESHelp._SlideCode);
if (string.IsNullOrEmpty(_cookie))
{
SlideVerifyCode();
return new Tuple<bool, string>(false, "请拖动滑块");
}
string _str = this._verificationCodeAESHelp.AES_Decrypt_Return_String(_cookie);
var sildeCodeModel = Newtonsoft.Json.JsonConvert.DeserializeObject<SlideVerifyCodeModel>(_str);
if (!sildeCodeModel.SlideCode)
{
return new Tuple<bool, string>(false, "请拖动滑块后点击汉字");
}
var _NowTime = DateTime.Now;
var _time = sildeCodeModel.timestamp;
var number = (_NowTime - _time).Minutes;
if (number > )
{
SlideVerifyCode();
return new Tuple<bool, string>(false, "滑块验证码过期");
}
return new Tuple<bool, string>(true, "成功");
} private void SlideVerifyCode(bool _bool = false)
{
var json = Newtonsoft.Json.JsonConvert.SerializeObject(new SlideVerifyCodeModel() { SlideCode = _bool, timestamp = DateTime.Now });
string base64Str = this._verificationCodeAESHelp.AES_Encrypt_Return_Base64String(json);
this._verificationCodeAESHelp.SetCookie(HttpContext, VerificationCodeAESHelp._SlideCode, base64Str, ); } }
}

Home

View

 @{
ViewData["Title"] = "Home Page";
Layout = null;
} <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>登录 </title> <link href="~/wwwroot/css/style.css" rel="stylesheet" />
<link href="~/wwwroot/css/slide-unlock.css" rel="stylesheet" /> <style>
body {
height: %;
background: #16a085;
overflow: hidden;
} canvas {
z-index: -;
position: absolute;
}
</style>
<script src="~/wwwroot/js/jquery1.11.1.js"></script> <script src="/wwwroot/js/Particleground.js" tppabs="js/Particleground.js"></script>
<script src="~/wwwroot/js/slide.js"></script> <script> $(document).ready(function () { $(".submit_btn").click(function () {
if ($("#labelTip").html() == "拖动滑块验证")
{
alert("请拖动滑块验证!");
return;
}
$.ajax({
url: "@Url.Action("Logins", "default")",
type: "post",
data: {
"userName": $("#userName").val(),
"passWord": $("#passWord").val()
},
success: function (d) {
if (d.status != "ok") {
alert(d.msg);
Slider_init();
} else {
alert(d.msg);
window.location.href = "@Url.Action("index")";
}
}
}) }) //粒子背景特效
$('body').particleground({
dotColor: '#5cbdaa',
lineColor: '#5cbdaa'
}); Slider_init();
}); function Slider_init() {
var slider = new SliderUnlock("#slider", {
successLabelTip: "验证成功"
}, function () { huadongCode();
});
slider.init();
} function huadongCode() {
num = ;
checkCode = [];
$.ajax({
type: "Post",
url: "@Url.Action("GetVerificationCodeImage", "Default")",
dataType: "json",
beforeSend: function (XMLHttpRequest) {
console.log(this); },
success: function (data) {
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>";
html += "<div id='divrefresh' style='width:20px;height:20px;position:absolute;cursor: pointer;margin-left: 90%;'> <img src=\"/wwwroot/images/shaxin.jpg\" /> </div>";
$("#huadongImage").css("display", "block").html(html);
$("#labelTip").html(data.msg);
imageClick();
divrefreshClick(); }
}) @* $.ajax({
"url": "@Url.Action("GetVerificationCodeImage","Default")",
"type": "get",
"success": function (data) {
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>";
html += "<div id='divrefresh' style='width:20px;height:20px;position:absolute;cursor: pointer;margin-left: 90%;'> <img src=\"/images/shaxin.jpg\" /> </div>";
$("#huadongImage").css("display", "block").html(html);
$("#labelTip").html(data.msg);
imageClick();
divrefreshClick();
},
"complete": function (XMLHttpRequest, status) {
if (status == 'timeout') { }
alert("");
}
})*@
} function divrefreshClick() {
$("#divrefresh").click(function () {
huadongCode();
num = ;
checkCode = [];
})
} var num = ;
var checkCode = [];
function createPoint(pos) {
if (num == ) {
PostcheckCode();
} $("#imagediv").append('<div class="point-area" onclick="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 - ) + 'px;left:' + parseInt(pos.x - ) + 'px;">' + num + '</div>');
++num;
} function PostcheckCode() {
$.ajax({
"url": "/Default/CheckCode",
"type": "post",
"data": {
"code": JSON.stringify(checkCode)
},
"success": function (d) {
if (d.status == "ok") {
$("#labelTip").html(d.msg);
$("#huadongImage").hide();
} else {
huadongCode();
}
},
"error": function (error) { }
}) } function pointClick(obj) {
num = ;
checkCode = [];
$(obj).parent().find('.point-area').remove();
} function getMousePos(obj, event) {
var e = event || window.event;
var x = e.clientX - ($(obj).offset().left - $(window).scrollLeft());
var y = e.clientY - ($(obj).offset().top - $(window).scrollTop());
checkCode.push({ "_X": parseInt(x), "_Y": parseInt(y) });
return { 'x': parseInt(x), 'y': parseInt(y) };
} function imageClick() {
$("#imagediv").click(function () {
var _this = $(this);
var pos = getMousePos(_this);
createPoint(pos);
}) }
</script>
</head>
<body>
<dl class="admin_login">
<dt>
<strong>登录</strong>
<em></em>
</dt>
<dd class="user_icon">
<input type="text" id="userName" placeholder="账号" class="login_txtbx" name="userName" data-val="true" data-val-required="賬號不能为空" />
<span class="field-validation-valid" data-valmsg-for="userName" data-valmsg-replace="true" style="color: #ff0000"></span>
</dd>
<dd class="pwd_icon">
<input type="password" id="passWord" placeholder="密码" class="login_txtbx" />
</dd>
<dd class="val_icon">
<div id="slider">
<div id="slider_bg"></div>
<span id="label">>></span>
<span id="labelTip">拖动滑块验证</span>
</div> <div id="huadongImage" style="width: 300px; border: 1px solid #ccc; height: 250px; z-index: 200; display: none; position: absolute; background-color: white; top: 40px;">
</div>
</dd>
<dd>
<input type="submit" value="立即登陆" class="submit_btn" />
</dd>
<dd></dd>
</dl>
</body>
</html>

View

样式请去http://www.bootcss.com/下载

.net MVC4一个登陆界面加验证的更多相关文章

  1. tkinter如何设置界面消失 当制作一个登陆界面时,登陆成功之后,如何让登陆界面本身消失

    tkinter如何设置界面消失 当制作一个登陆界面时,登陆成功之后,如何让登陆界面本身消失 if querySQL.checkAll():#用户名和密码都输入正确 self.root.withdraw ...

  2. Android UI组件----用相对布局RelativeLayout做一个登陆界面

    [声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/3 ...

  3. java swing 制作一个登陆界面,亲测有效

    一.介绍 Swing 是一个为Java设计的GUI工具包. Swing是JAVA基础类的一部分. Swing包括了图形用户界面(GUI)器件如:文本框,按钮,分隔窗格和表. Swing提供许多比AWT ...

  4. 编写代码:ATM的登陆界面(用户验证、主菜单的选择) 查询-- 存款-- 取款-- 退出

    #include <stdio.h>#include <windows.h>int main (void){    int password,one,two,money1=10 ...

  5. Html飞机大战(四):状态的切换(界面加载类的编辑)

    好家伙,接着写   既然我们涉及到状态了,那么我们也会涉及到状态的切换   那么我们怎样切换状态呢? 想象一下,如果我玩的游戏暂停了,那么我们肯定是通过点击或者按下某个按键来让游戏继续   这里我们选 ...

  6. Unity进阶:用AssetBundle和Json做了一个玩家登陆界面

    版权申明: 本文原创首发于以下网站: 博客园『优梦创客』的空间:https://www.cnblogs.com/raymondking123 优梦创客的官方博客:https://91make.top ...

  7. 一个网页登陆界面写30多个测试Case——测试之道

    转自博文:http://www.cnblogs.com/I-am-Betty/p/3566411.html 具体需求: 有一个登陆页面, (假如上面有2个textbox, 一个提交按钮. 请针对这个页 ...

  8. 一个简单WPF登陆界面,包含记住密码,自动登录等功能,简洁美观

    简介:这是一个自己以前用WPF设计的登陆界面,属于一个实验性的界面窗体,如果用于产品还很有不足.但也是有一点学习价值.后台代码略有复杂,但基本上都有注释 分类,略有代码经验的一般都能看懂. 登陆界面外 ...

  9. 用Html写一个简单的登陆界面

    <!DOCTYPE html> <html> <title>登陆页面</title> <head> <meta charset=&qu ...

随机推荐

  1. datatable to List<T>带缓存

    public class DataHelper { //datarow 转换的类型缓存 private static MemoryCache modelCash = MemoryCache.Defau ...

  2. adsas数据库去O记

    adsas 数据库是用于广告买量数据分析;在17年由 Oracle 迁移到 PostgreSQL.现把之前的迁移笔记整理下.本次迁移表91个:存储过程21个:数据库大小2G. 1. 准备Postgre ...

  3. python使用requests发送text/xml报文数据

    def client_post_xmldata_requests(request_url,requestxmldata): #功能说明:发送请求报文到指定的地址并获取请求响应报文 #输入参数说明:接收 ...

  4. POI导出Excel发现不可读取的内容

    环境说明:MyEclipse Tomcat7.0 通过后台查询数据,导出Excel在打开时会出现以下提示: 点击否,则不显示任何内容,点击是,弹出 查看修改记录为: 通过WPS打开不会出现任何提示,可 ...

  5. 【Zookeeper系列】ZooKeeper安装配置(转)

    原文链接:https://www.cnblogs.com/sunddenly/p/4018459.html 一.Zookeeper的搭建方式 Zookeeper安装方式有三种,单机模式和集群模式以及伪 ...

  6. STM32进入HardFault_Handler处理办法

    STM32进入HardFault_Handler处理办法 HardFault_Handler出现的情况一般有两种: 一种是:数组越界 一种是:堆栈溢出,程序指针指飞 方法一 在中断HardFault_ ...

  7. gym 101858

    我这个傻逼被治了一下午. 大好的橘势,两个小时6T,去看L,哇傻逼题.然后我跑的最短路T到自闭 最后十几分钟去想了下A,一直在想如何表示状态..就是想不到二进制搞一下... 然后游戏结束了..以后我就 ...

  8. 算法提高 最小方差生成树(Kruskal)_模板

     算法提高 最小方差生成树   时间限制:1.0s   内存限制:256.0MB        问题描述 给定带权无向图,求出一颗方差最小的生成树. 输入格式 输入多组测试数据.第一行为N,M,依次是 ...

  9. php算法题2

    一群猴子排成一圈,按1,2,…,n依次编号.然后从第1只开始数,数到第m只,把它踢出圈,从它后面再开始数,再数到第m只,在把它踢出去…,如此不停的进行下去,直到最后只剩下一只猴子为止,那只猴子就叫做大 ...

  10. __super:: 使用

    它会调用 基类的函数方法实现. __super::Close(); __super::Find();