现在很多网页登陆的时候都使用了随机图片的方式,是一种简单、有效的防止黑客恶意攻击的手段。今天看了一些网上的资料,明白其生成原理:从样本中,获取随机字符串,随机字符串保存进session,并以位图的方式形成随机码图片。
实现:
添加命名空间
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
生成页代码
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
public partial class getRandImg : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//生成随机码图片
SetValidateCode();
//生成页面不保存到cache
Response.Cache.SetNoStore();
}
//设置验证码
private void SetValidateCode()
{
//新建位图
Bitmap newBitmap = new Bitmap(
71,
23,
PixelFormat.Format32bppArgb
);
//从位图获得绘图画面
Graphics g = Graphics.FromImage(newBitmap);
//随机数生成器
Random r = new Random();
//绘图画面清空
g.Clear(Color.White);
//绘图画面划线干扰
for (int i = 0; i < 50; i++)
{
int x1 = r.Next(newBitmap.Width);
int x2 = r.Next(newBitmap.Width);
int y1 = r.Next(newBitmap.Height);
int y2 = r.Next(newBitmap.Height);
g.DrawLine(new Pen(
Color.FromArgb(r.Next())),
x1,
&nb
···
···