`
oraclestudy
  • 浏览: 482521 次
文章分类
社区版块
存档分类

ASP.NET 使用验证码来维护网站性能

 
阅读更多

登陆页面

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="MyBlog_Login" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Login</title>
<link type="text/css" rel="Stylesheet" href="../css/Common.css" />

<script language="javascript" type="text/javascript">
var a=0;
function btnLogin_onclick() {
var acc=document.getElementById("txtAccount").value;
var key=document.getElementById("txtPwd").value;
var checkCode=document.getElementById("txtCheckCode").value;
window.location.href="MyBlogMain.aspx?Acc="+acc+"&Key="+key+"&CheckCode="+checkCode;
}
document.onkeydown = function()
{
if(event.keyCode == 13)
{
document.getElementById("btnLogin").click();
}
}

</script>


</head>
<body>
<form id="form1" runat="server">
<div style="height: 100px;">
</div>
<div>
<div id="LoginMain" style="margin: auto; text-align: center; width: 400px; border: #444444 1px solid">
<div id="Logo" style="height: 200px;">
<div id="LogoImage" style="background: url(../image/default/logo_cn.gif) center no-repeat;
height: 180px;">
</div>
</div>
<div style="margin: 10px 0px 0px 0px; text-align: center; width: 260px;">
<div id="Account" style="height: 25px; line-height: 25px;">
<div id="AccountText" style="float: left; width: 55px; text-align: right; font-size: 10pt;">
帐&nbsp;&nbsp;&nbsp;&nbsp;户</div>
<div id="AccountInput" style="float: left">
<input type="text" id="txtAccount" style="width: 175px" class="userinput" tabindex="1"/></div>
</div>
<div id="Key" style="height: 25px; line-height: 25px;">
<div id="KeyText" style="float: left; width: 55px; text-align: right; font-size: 10pt;">
密&nbsp;&nbsp;&nbsp;&nbsp;码</div>
<div id="KeyInput" style="float: left;">
<input type="password" id="txtPwd" style="width: 175px" class="userinput" tabindex="2"/></div>
</div>
<div id="CheckImage" style="height: 25px; line-height: 25px;">
<div style="float: left; width: 55px;">
</div>
<div style="float: left; width: 200px">
<iframe width="180px" height="24px" src="CheckCode.aspx" style="float: left" marginheight="0"
marginwidth="0" frameborder="0" scrolling="no"></iframe>
</div>
</div>
<div id="CheckCode" style="height: 25px; line-height: 25px;">
<div id="CheckCodeText" style="float: left; width: 55px; text-align: right; font-size: 10pt;">
验证码</div>
<div id="CheckCodeInput" style="float: left; width: 200px;">
<div style="float: left">
<input type="text" id="txtCheckCode" style="width: 85px;" class="userinput" tabindex="3"/>
</div>
</div>
</div>
<div id="DoLogin" style="height: 25px; line-height: 25px; clear: both; margin: 10px 0px 10px 0px;">
<input type="button" id="btnLogin" value="登 录" runat="server" onclick="return btnLogin_onclick()" tabindex="4"/>
</div>
</div>
</div>
</div>
</form>
</body>
</html>
<script language="javascript" type="text/javascript">
//不能用select!
document.getElementById("txtAccount").focus();
</script>
验证码页面

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CheckCode.aspx.cs" Inherits="MyBlog_CheckCode" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<style type="text/css">
a:link
{
font-weight: bold;
text-decoration: none;
color: #000000;
border: 0px solid #ffffff;
padding: 0px;
margin: 0px;
}
a:visited
{
font-weight: bold;
text-decoration: none;
color: #000000;
border: 0px solid #ffffff;
padding: 0px;
margin: 0px;
}
a:hover
{
font-weight: bold;
text-decoration: none;
color: #000000;
border: 0px solid #ffffff;
padding: 0px;
margin: 0px;
}
a:active
{
font-weight: bold;
text-decoration: none;
color: #000000;
border: 0px solid #ffffff;
padding: 0px;
margin: 0px;
}
</style>

<script language="javascript" type="text/javascript">
function RePost()
{
window.location.href="CheckCode.aspx";
}
//document.onreadystatechange = function()
//{
// if(document.readyState=="complete")
// {
// window.parent.document.getElementById("hidCheckCode").value=document.getElementById("hidCheckCode").value
// }
//}
</script>

</head>
<body>
<form id="form1" runat="server">
<div style="float: left; width: 180px;">
<div style="float: left">
<img id="imgCheckCode" style="border: 0px solid #ffffff; margin: 0px; padding: 0px;"
runat="server" onclick="RePost()" alt="看不清楚?请点击!"/>
</div>
<div style="float: left; font-family: 宋体; font-size: 12pt;">
<a href="CheckCode.aspx" style="border: 0px solid #ffffff; margin: 0px; padding: 0px;
text-align: " tabindex="-1">看不清?</a>
</div>
<!--<input type="hidden" id="hidCheckCode" value="" runat="server"/>-->
</div>
</form>
</body>
</html>
验证码服务器端

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using RongPan.TuDou.Common;

public partial class MyBlog_CheckCode : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string checkCode = Code.NextCheckCode();
//验证数据必须保存在服务器上
Session["CheckCode"] = CheckCodeImage.GetCheckCodeHash(checkCode);

this.imgCheckCode.Src = "CheckCodeImage.aspx?CheckCode="+checkCode;
}
}
验证码图片服务器端(最好做成ashx简单处理页)

using System;
using System.Web;
using System.Web.UI;

public partial class MyBlog_CheckCodeImage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string checkCode=Request["CheckCode"];
if (checkCode!=null&&checkCode.Length>3&&checkCode.Length<7)
{
RongPan.TuDou.Common.CheckCodeImage.CreateCheckCodeImage(checkCode,this.Response);
}
}
}
生成验证码的基础类

using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;

namespace RongPan.TuDou.Common
{
public class CheckCodeImage
{
/// <summary>
/// 生成验证码图片
/// </summary>
/// <param name="checkCode"></param>
/// <param name="response"></param>
public static void CreateCheckCodeImage(string checkCode, System.Web.HttpResponse response)
{
int width = 80;//验证码图片宽度
int height = 22;//验证码图片高度
Font font = new Font("Arial", 12, FontStyle.Bold);//验证码字体

SolidBrush brush = new SolidBrush(Color.Black);//用于写验证码的画笔

Pen crosswise = new Pen(Color.Green, 0);//画横向干扰线的钢笔
Pen vertical = new Pen(Color.FromArgb(255, 100, 100, 100), 0);//画纵向干扰线的钢笔

Bitmap image = new Bitmap(width, height);//生成图像

Graphics g = Graphics.FromImage(image);//生成一个绘画面板(画布)

g.Clear(ColorTranslator.FromHtml("#f0f0f0"));//用指定颜色填充画布

RectangleF rect = new RectangleF(5, 2, width, height);//定义文字的绘制矩形

Random rand = new Random((int)DateTime.Now.Ticks);//生成干扰线的随机对象

for (int i = 0; i < 2; i++)
{
Point start = new Point(0, rand.Next(height));

Point end = new Point(width, rand.Next(height));

g.DrawLine(crosswise, start, end);
}

for (int i = 0; i < 4; i++)
{
Point start = new Point(rand.Next(width), 0);

Point end = new Point(rand.Next(width), height);

g.DrawLine(vertical, start, end);
}

g.DrawString(checkCode,font,brush,rect);//将验证码写到画布上
System.IO.MemoryStream ms = new System.IO.MemoryStream();
try
{
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
response.ClearContent();
response.ContentType = "image/Gif";
response.BinaryWrite(ms.ToArray());
}
finally
{
ms.Flush();
ms.Close();
ms.Dispose();
g.Dispose();
image.Dispose();
}
}
/// <summary>
/// 生成验证码的HashCode
/// </summary>
/// <param name="checkCode"></param>
/// <returns></returns>
public static string GetCheckCodeHash(string checkCode)
{
return Code.GetSHA1HashCode(checkCode.Trim().ToUpper());
}
}
}
用于加密的基础类

using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;

namespace RongPan.TuDou.Common
{
public class Code
{
/// <summary>
/// 获得字符串的MD5编码,速度快
/// </summary>
/// <param name="input">需要加密的字符串</param>
/// <returns>MD5 Code</returns>
public static string GetMd5HashCode(string input)
{
//
// Create a new instance of the MD5CryptoServiceProvider object.
MD5 md5Hasher = MD5.Create();

// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();

// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
foreach (byte b in data)
{
sBuilder.Append(b.ToString("x2"));
}

// Return the hexadecimal string.
return sBuilder.ToString();
}
/// <summary>
/// 获得字符串的SHA1编码,更安全
/// </summary>
/// <param name="input">需要加密的字符串</param>
/// <returns>SHA1 Code</returns>
public static string GetSHA1HashCode(string input)
{
//
byte[] data = Encoding.Default.GetBytes(input);
byte[] result;

SHA1 sha = new SHA1CryptoServiceProvider();
// This is one implementation of the abstract class SHA1.
result = sha.ComputeHash(data);

StringBuilder sBuilder = new StringBuilder();
foreach(byte b in result)
{
sBuilder.Append(b.ToString("x2"));
}

return sBuilder.ToString();
}
/// <summary>
/// 获得全局唯一标识
/// </summary>
/// <returns></returns>
public static string GetGUID()
{
return Guid.NewGuid().ToString().Replace('-', '/0');
}
/// <summary>
/// 编码
/// </summary>
/// <param name="var"></param>
/// <returns></returns>
public static string DoCode(string var)
{
string code = string.Empty;
//进行编码
return code;
}
/// <summary>
/// 反编码
/// </summary>
/// <param name="code"></param>
/// <returns></returns>
public static string DeCode(string code)
{
string var = string.Empty;
//进行反编码
return var;
}
/// <summary>
/// 生成指定长度英文字母
/// </summary>
/// <param name="codeCount"></param>
/// <returns></returns>
public static string NextCheckCode(int codeCount)
{
string[] allChar = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", " K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "W", " X", "Y", "Z " };
Random rnd = new Random((int)DateTime.Now.Ticks);
StringBuilder code = new StringBuilder();
for (int i = 0; i < codeCount; i++)
{
code.Append(allChar[rnd.Next(0, 25)]);
}
return code.ToString().Replace(" ","");
}
/// <summary>
/// 生成5位随机英文字母
/// </summary>
/// <returns></returns>
public static string NextCheckCode()
{
return NextCheckCode(5);
}
}
}
最后用来验证的页面服务器端

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using RongPan.TuDou.Common;

public partial class MyBlog_MyBlogMain : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string checkCode = Request["CheckCode"];
string hashCode = string.Empty;

Object temp = Session["CheckCode"];
if(temp!=null)hashCode = temp.ToString().Trim();

if (checkCode != null && checkCode.Length > 3 && checkCode.Length < 7&&hashCode!=null&&hashCode.Length>0)
{
string reHashCode = CheckCodeImage.GetCheckCodeHash(checkCode);
if (hashCode == reHashCode)
{
Response.Write("<script language='javascript' type='text/javascript'>alert('ok!');</script>");
}
}
}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics