.net MVC4一个登陆界面加验证

时间:2023-12-19 08:47:32

.net  MVC4一个登陆界面加验证

.net  MVC4一个登陆界面加验证

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/下载