为防止暴力注册提交数据,设计图片验证码成为必要。
之前用Label存储如"1+3=?"不可取,因用document.getIdByElement()可以获取到答案,成为掩耳盗铃,此地无银300两之举措。现在改成图片验证且编码保存在Session内破解难度就大了!
源代码如下:
1.生成图片验证码的类(业务类)
Code
using System;
using System.Data;
using System.Web;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.WebControls;
using vjsdn.globals;
using System.Drawing.Drawing2D;
namespace vjsdn.SystemSecurityLibrary
{
/// <summary>
/// 生成图片验证码
/// </summary>
public class CGenValidateCode
{
#region 随机字符验证码
private Page _page = null;
public CGenValidateCode(Page page)
{
_page = page;
}
/// <summary>
/// 产生验证码
/// </summary>
/// <returns></returns>
private string CreateCode(int codeLength)
{
string chars = "1,2,3,4,5,6,7,8,9,0,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z," +
"A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
string[] strArr = chars.Split(’,’);
string code = "";
Random rand = new Random();
for (int i = 0; i < codeLength; i++)
{
code += strArr[rand.Next(0, strArr.Length)];
}
return code;
}
/// <summary>
/// 输出验证图片
/// </summary>
/// <param name="code"></param>
private void CreateImage(string code)
{
Bitmap image = new Bitmap(70, 20); //验证码图片模块
Graphics g = Graphics.FromImage(image);
WebColorConverter ww = new WebColorConverter();
g.Clear((Color)ww.ConvertFromString("#dadada")); //底色
Random random = new Random();
//画图片的背景噪音线
for (int i = 0; i < 12; i++)
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);
g.DrawLine(new Pen(Color.LightGray), x1, y1, x2, y2);
}
//验证码字体
Font font = new Font("arial", 13, FontStyle.Bold | FontStyle.Italic);
//画笔对象
LinearGradientBrush brush = new LinearGradientBrush(
new Rectangle(0, 0, image.Width, image.Height), Color.Red, Color.Gray, 1.2f, true);
g.DrawString(code, font, brush, 0, 0);
//画图片的前景噪音点
for (int i = 0; i < 10; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, Color.White);
}
//画图片的边框线
g.DrawRectangle(new Pen(Color.Gray), 0, 0, image.Width - 1, image.Height - 1);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
_page.Response.ClearContent();
_page.Response.ContentType = "image/Gif"; //HTTP MIME TYPE 设为图片输出
_page.Response.BinaryWrite(ms.ToArray());
g.Dispose();
image.Dispose();
}
/// <summary>
/// 生成新的验证码
/// </summary>
public void Generate()
{
string checkCode = this.CreateCode(5); //生成新的验证码
_page.Session["_MyCode"] = checkCode;
this.CreateImage(checkCode);
}
/// <summary>
/// 检验用户输入的验证码
/// </summary>
/// <param name="validatePage">要验证的页面</param>
/// <param name="input">用户输入的验证码</param>
/// <returns></returns>
public static bool ValidateLastCode(Page validatePage, string input)
{
//将对象转换为字符串
string lastCode = Convert.ToString(validatePage.Session["_MyCode"]);
return (input.ToUpper() == lastCode.ToUpper());
}
#endregion
}
}
2.编写CreateValidateImg.aspx页面,用来生成图片。代码很少,在Page_Load事件内创建对象就行了! using System;
using System.Data;
using System.Web;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.WebControls;
using vjsdn.globals;
using System.Drawing.Drawing2D;
namespace vjsdn.SystemSecurityLibrary
{
/// <summary>
/// 生成图片验证码
/// </summary>
public class CGenValidateCode
{
#region 随机字符验证码
private Page _page = null;
public CGenValidateCode(Page page)
{
_page = page;
}
/// <summary>
/// 产生验证码
/// </summary>
/// <returns></returns>
private string CreateCode(int codeLength)
{
string chars = "1,2,3,4,5,6,7,8,9,0,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z," +
"A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
string[] strArr = chars.Split(’,’);
string code = "";
Random rand = new Random();
for (int i = 0; i < codeLength; i++)
{
code += strArr[rand.Next(0, strArr.Length)];
}
return code;
}
/// <summary>
/// 输出验证图片
/// </summary>
/// <param name="code"></param>
private void CreateImage(string code)
{
Bitmap image = new Bitmap(70, 20); //验证码图片模块
Graphics g = Graphics.FromImage(image);
WebColorConverter ww = new WebColorConverter();
g.Clear((Color)ww.ConvertFromString("#dadada")); //底色
Random random = new Random();
//画图片的背景噪音线
for (int i = 0; i < 12; i++)
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);
g.DrawLine(new Pen(Color.LightGray), x1, y1, x2, y2);
}
//验证码字体
Font font = new Font("arial", 13, FontStyle.Bold | FontStyle.Italic);
//画笔对象
LinearGradientBrush brush = new LinearGradientBrush(
new Rectangle(0, 0, image.Width, image.Height), Color.Red, Color.Gray, 1.2f, true);
g.DrawString(code, font, brush, 0, 0);
//画图片的前景噪音点
for (int i = 0; i < 10; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, Color.White);
}
//画图片的边框线
g.DrawRectangle(new Pen(Color.Gray), 0, 0, image.Width - 1, image.Height - 1);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
_page.Response.ClearContent();
_page.Response.ContentType = "image/Gif"; //HTTP MIME TYPE 设为图片输出
_page.Response.BinaryWrite(ms.ToArray());
g.Dispose();
image.Dispose();
}
/// <summary>
/// 生成新的验证码
/// </summary>
public void Generate()
{
string checkCode = this.CreateCode(5); //生成新的验证码
_page.Session["_MyCode"] = checkCode;
this.CreateImage(checkCode);
}
/// <summary>
/// 检验用户输入的验证码
/// </summary>
/// <param name="validatePage">要验证的页面</param>
/// <param name="input">用户输入的验证码</param>
/// <returns></returns>
public static bool ValidateLastCode(Page validatePage, string input)
{
//将对象转换为字符串
string lastCode = Convert.ToString(validatePage.Session["_MyCode"]);
return (input.ToUpper() == lastCode.ToUpper());
}
#endregion
}
}
Code
public partial class CreateValidateImg : System.Web.UI.Page
{
private CGenValidateCode _gen = null;
protected void Page_Load(object sender, EventArgs e)
{
_gen = new CGenValidateCode(this);
_gen.Generate();
}
}
3. 验证码应用,比如系统登录. public partial class CreateValidateImg : System.Web.UI.Page
{
private CGenValidateCode _gen = null;
protected void Page_Load(object sender, EventArgs e)
{
_gen = new CGenValidateCode(this);
_gen.Generate();
}
}
HTML Code 图片链接地址:
<img id="vcode" alt="" src="CreateValidateImg.aspx" />
如果产生的验证码看不清楚,加下面这段代码. getTime函数用来避免只能点一次链接。
<a href="#" οnclick="document.getElementById(’vcode’).src=’CreateValidateImg.aspx?temp=’+
( new Date().getTime().toString(36)); return false;">重新生成验证码</a>
C# Code 登录按钮Click事件
Code
protected void btnLogin_Click(object sender, EventArgs e)
{
//在Login按钮内检查验证码,TextBox1.Text为用户输入的验证码,
//通过类方法检查验证码.
bool ret = CGenValidateCode.ValidateLastCode(this, TextBox1.Text);
if (ret)
this.Response.Write("用户输入验证码正确");
else
this.Response.Write("用户输入验证码错误");
}
有图为证: protected void btnLogin_Click(object sender, EventArgs e)
{
//在Login按钮内检查验证码,TextBox1.Text为用户输入的验证码,
//通过类方法检查验证码.
bool ret = CGenValidateCode.ValidateLastCode(this, TextBox1.Text);
if (ret)
this.Response.Write("用户输入验证码正确");
else
this.Response.Write("用户输入验证码错误");
}
如转载请注明出自易学论坛 http://www.vjsdn.com/