用户在注册或登录时,为了进一步保证安全性,越来越多的网站开始采用动态生成的图形码或附加码进行验证。验证码技术就是在服务器端生成一个随机数,并将其保存在内存中,然后将随机数写入设计好的图片中,发送给浏览器,并以图片形式显示给最终用户。前几天,在完成一个利用Script进行用户注册及登录的验证时,在加入验证码这一块的时候,发现了各种生成验证码的方式,就利用空余时间做了一个整理及重写。那么我的博客之旅就从这篇验证码的生成开始了。
下面主要是几种不同的生成验证码的方式:
1、绘制纯数字的网站验证码
本实例实现的是数字验证码技术,即随机生成4位数字作为验证码。在开发绘制会员登录验证模块时可以使用数字验证码技术。
■设计过程
在一个新建的窗体CheckCode.aspx中编写生成数字验证码的方法:
private string RndNum()
{
int number;
char code;
string checkCode = String.Empty;
System.Random random = new Random();
for (int i = 0; i < 4; i++)
{
number = random.Next();
if (number % 2 == 0)
code = (char)('0' + (char)(number % 10));
else
code = (char)('A' + (char)(number % 26));
checkCode += code.ToString();
}
Response.Cookies.Add(new HttpCookie("yzmcode", checkCode));
return checkCode;
}
private void CreateCheckCodeImage(string checkCode)
{
if (checkCode == null || checkCode.Trim() == String.Empty)
return;
System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
Graphics g = Graphics.FromImage(image);
try
{
//生成随机生成器
Random random = new Random();
//清空图片背景色
g.Clear(Color.White);
//画图片的背景噪音线
for (int i = 0; i < 25; 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.Silver), x1, y1, x2, y2);
}
Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
System.Drawing.Drawing2D.LinearGradientBrush brush = new
System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
Color.Blue, Color.DarkRed, 1.2f, true);
g.DrawString(checkCode, font, brush, 2, 2);
//画图片的前景噪音点
for (int i = 0; i < 100; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(random.Next()));
}
//画图片的边框线
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
Response.ClearContent();
Response.ContentType = "image/Gif";
Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}
然后在Page_Load中调用CreateCheckCodeImage():
protected void Page_Load(object sender, EventArgs e)
{
this.CreateCheckCodeImage(RndNum());
}
那么在我们登录的窗口中就可以通过简单的控件:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/CheckCode.aspx" Width="50" Height="30"/><asp:Label
ID="Label1" runat="server" Text="看不清楚?点击图片换一个" Height="16px"
Font-Size="Small" ForeColor="Red"></asp:Label>
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
在Button1_Click中对验证码输入的正确性进行判断:
protected void Button1_Click(object sender, EventArgs e)
{
if (String.Compare(Request.Cookies["yzmcode"].Value, TextBox1.Text, true) != 0)
{
Response.Write("<script>alert('验证码错误!')</script>");
}
else
Response.Write("<script>alert('验证码正确!')</script>");
}
2、绘制数字与字母组合的网站验证码
和纯数字的很相似,具体区别在随机生成字符串的方法中
private string GenerateCheckCode()
{
int number;
char code;
string checkCode = String.Empty;
Random random = new Random();
for (int i = 0; i < 4; i++)
{
number = random.Next();
if (number % 2 == 0)
code = (char)('0' + (char)(number % 10));
else
code = (char)('A' + (char)(number % 26));
checkCode += code.ToString();
}
Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));
return checkCode;
}
字符串生成后,接下来就是将该字符串绘制成图片显示出来。代码如下:
private void CreateCheckCodeImage(string checkCode)
{
if (checkCode == null || checkCode.Trim() == String.Empty)
return;
System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22); Graphics g = Graphics.FromImage(image);
try
{
//生成随机生成器
Random random = new Random();
//清空图片背景色
g.Clear(Color.White);
//画图片的背景噪音线
for (int i = 0; i < 2; 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.Black), x1, y1, x2, y2);
}
Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold));
System.Drawing.Drawing2D.LinearGradientBrush brush = new
System.Drawing.Drawing2D.LinearGradientBrush(
new Rectangle(0, 0, image.Width, image.Height),
Color.Blue, Color.DarkRed, 1.2f, true);
g.DrawString(checkCode, font, brush, 2, 2);
//画图片的前景噪音点
for (int i = 0; i < 100; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(random.Next()));
}
//画图片的边框线
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
Response.ClearContent();
Response.ContentType = "image/Gif";
Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}
在登录的窗口进行验证码输入是否正确的判断:
protected void Button1_Click(object sender, EventArgs e)
{
HttpCookie cookie = Request.Cookies["CheckCode"];
if (cookie.Value == this.TextBox1.Text.Trim())
{
Response.Write("<script>alert('验证码正确!')</script>");
}
else
{
Response.Write("<script>alert('验证码错误!')</script>");
}
}
那么有关于数字与字母组合的网站验证码就生成了。
3、四则运算式的验证码
其他的和数字和字母混合生成的验证码相似,我就不写了,具体区别在随机生成四则运算式的方法中,如下:
private string GenerateCheckCode()
{
Random rd = new Random();
int Results = 0;
int Num1 = rd.Next(10);
int Num2 = rd.Next(10);
string Expressions = "";
int F = (rd.Next(4) + 1);
switch (F)
{
case 1:
Results = Num1 + Num2;
Expressions = Num1 + "+" + Num2;
break;
case 2:
Results = Num1 - Num2;
Expressions = Num1 + "-" + Num2;
break;
case 3:
Results = Num1 * Num2;
Expressions = Num1 + "*" + Num2;
break;
case 4:
if (Num2 > 0)
{
Results = Convert.ToInt16(Num1 / Num2);
Expressions = Num1 + "/" + Num2;
}
else
{
Results = Num1;
Expressions = Num1 + "/1";
}
break;
}
Session["Code"] = Results.ToString();
return Expressions;
}
这篇主要讲了三种方法,在下一篇中会介绍另一种方法——中文彩色验证码,因代码篇幅较长就放在下一篇中介绍了。