验证码(CAPTCHA)是“Completely Automated Public Turing test to tell Computers and Humans Apart”(全自动区分计算机和人类的图灵测试) 的缩写,是一种区分用户是计算机和人的公共全自动程序。可以防止:恶意破解密码、刷票、论坛灌水,有效防止某个黑客对某一个特定注册用户用特定程序暴力破 解方式进行不断的登陆尝试,实际上是用验证码是现在很多网站通行的方式(比如招商银行的网上个人银行,百度社区),我们利用比较简易的方式实现了这个功 能。目前,不少网站为了防止用户利用机器人自动注册、登录、灌水,都采用了验证码技术。所谓验证码,就是将一串随机产生的数字或符号,生成一幅图片, 图片里加上一些干扰,例如随机画数条直线,画一些点(防止OCR),由用户肉眼识别其中的验证码信息,输入表单提交网站验证,验证成功后才能使用某项功 能。

今天我们一起来实现一个基于Session原理的验证码方案,基本步骤是这样的:用户打开页面 --> 在服务器端用随机字母和数字生成图片,并对图片进行扭曲、渲染等操作 --> 将刚才图片的字符存入服务器Session --> 用户提交数据之前比较用户输入的验证码和服务器端保存的验证码 --> 成功后清空服务器端保存在Session中的验证码。

随机生成字符图片类的代码如下:

using System.Data;
using System.Drawing;
using System.Web;
 
namespace verifycode_session
{
    public class VerifyCode
    {
 
        #region 验证码长度(默认6个验证码的长度)
        int length = 6;
        public int Length
        {
            get { return length; }
            set { length = value; }
        }
        #endregion
 
        #region 验证码字体大小(为了显示扭曲效果,默认40像素,可以自行修改)
        int fontSize = 40;
        public int FontSize
        {
            get { return fontSize; }
            set { fontSize = value; }
        }
        #endregion
 
        #region 边框补(默认1像素)
        int padding = 2;
        public int Padding
        {
            get { return padding; }
            set { padding = value; }
        }
        #endregion
 
        #region 是否输出燥点(默认输出)
        bool chaos = true;
        public bool Chaos
        {
            get { return chaos; }
            set { chaos = value; }
        }
        #endregion
 
        #region 输出燥点的颜色(默认灰色)
        Color chaosColor = Color.LightGray;
        public Color ChaosColor
        {
            get { return chaosColor; }
            set { chaosColor = value; }
        }
        #endregion
 
        #region 自定义背景色(默认白色)
        Color backgroundColor = Color.White;
        public Color BackgroundColor
        {
            get { return backgroundColor; }
            set { backgroundColor = value; }
        }
        #endregion
 
        #region 自定义随机颜色数组
        Color[] colors = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
        public Color[] Colors
        {
            get { return colors; }
            set { colors = value; }
        }
        #endregion
 
        #region 自定义字体数组
        string[] fonts = { "Arial", "Georgia" };
        public string[] Fonts
        {
            get { return fonts; }
            set { fonts = value; }
        }
        #endregion
 
        #region 自定义随机码字符串序列(使用逗号分隔)
        string codeSerial = "1,2,3,4,5,6,7,8,9,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";
        public string CodeSerial
        {
            get { return codeSerial; }
            set { codeSerial = value; }
        }
        #endregion
 
        #region 产生波形滤镜效果
 
        private const double PI = 3.1415926535897932384626433832795;
        private const double PI2 = 6.283185307179586476925286766559;
 
        /// <summary>
        /// 正弦曲线Wave扭曲图片(Edit By 51aspx.com)
        /// </summary>
        /// <param name="srcBmp">图片路径</param>
        /// <param name="bXDir">如果扭曲则选择为True</param>
        /// <param name="nMultValue">波形的幅度倍数,越大扭曲的程度越高,一般为3</param>
        /// <param name="dPhase">波形的起始相位,取值区间[0-2*PI)</param>
        /// <returns></returns>
        public System.Drawing.Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase)
        {
            System.Drawing.Bitmap destBmp = new Bitmap(srcBmp.Width, srcBmp.Height);
 
            // 将位图背景填充为白色
            System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(destBmp);
            graph.FillRectangle(new SolidBrush(System.Drawing.Color.White), 0, 0, destBmp.Width, destBmp.Height);
            graph.Dispose();
 
            double dBaseAxisLen = bXDir ? (double)destBmp.Height : (double)destBmp.Width;
 
            for (int i = 0; i < destBmp.Width; i++)
            {
                for (int j = 0; j < destBmp.Height; j++)
                {
                    double dx = 0;
                    dx = bXDir ? (PI2 * (double)j) / dBaseAxisLen : (PI2 * (double)i) / dBaseAxisLen;
                    dx += dPhase;
                    double dy = Math.Sin(dx);
 
                    // 取得当前点的颜色
                    int nOldX = 0, nOldY = 0;
                    nOldX = bXDir ? i + (int)(dy * dMultValue) : i;
                    nOldY = bXDir ? j : j + (int)(dy * dMultValue);
 
                    System.Drawing.Color color = srcBmp.GetPixel(i, j);
                    if (nOldX >= 0 && nOldX < destBmp.Width
                     && nOldY >= 0 && nOldY < destBmp.Height)
                    {
                        destBmp.SetPixel(nOldX, nOldY, color);
                    }
                }
            }
 
            return destBmp;
        }
 
        #endregion
 
        #region 生成校验码图片
        public Bitmap CreateImageCode(string code)
        {
            int fSize = FontSize;
            int fWidth = fSize + Padding;
 
            int imageWidth = (int)(code.Length * fWidth) + 4 + Padding * 2;
            int imageHeight = fSize * 2 + Padding;
 
            System.Drawing.Bitmap image = new System.Drawing.Bitmap(imageWidth, imageHeight);
 
            Graphics g = Graphics.FromImage(image);
 
            g.Clear(BackgroundColor);
 
            Random rand = new Random();
 
            //给背景添加随机生成的燥点
            if (this.Chaos)
            {
 
                Pen pen = new Pen(ChaosColor, 0);
                int c = Length * 10;
 
                for (int i = 0; i < c; i++)
                {
                    int x = rand.Next(image.Width);
                    int y = rand.Next(image.Height);
 
                    g.DrawRectangle(pen, x, y, 1, 1);
                }
            }
 
            int left = 0, top = 0, top1 = 1, top2 = 1;
 
            int n1 = (imageHeight - FontSize - Padding * 2);
            int n2 = n1 / 4;
            top1 = n2;
            top2 = n2 * 2;
 
            Font f;
            Brush b;
 
            int cindex, findex;
 
            //随机字体和颜色的验证码字符
            for (int i = 0; i < code.Length; i++)
            {
                cindex = rand.Next(Colors.Length - 1);
                findex = rand.Next(Fonts.Length - 1);
 
                f = new System.Drawing.Font(Fonts[findex], fSize, System.Drawing.FontStyle.Bold);
                b = new System.Drawing.SolidBrush(Colors[cindex]);
 
                if (i % 2 == 1)
                {
                    top = top2;
                }
                else
                {
                    top = top1;
                }
 
                left = i * fWidth;
 
                g.DrawString(code.Substring(i, 1), f, b, left, top);
            }
 
            //画一个边框 边框颜色为Color.Gainsboro
            g.DrawRectangle(new Pen(Color.Gainsboro, 0), 0, 0, image.Width - 1, image.Height - 1);
            g.Dispose();
 
            //产生波形(Add By 51aspx.com)
            image = TwistImage(image, true, 8, 4);
 
            return image;
        }
        #endregion
 
        #region 将创建好的图片输出到页面
        public void CreateImageOnPage(string code, HttpContext context)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            Bitmap image = this.CreateImageCode(code);
 
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
 
            context.Response.ClearContent();
            context.Response.ContentType = "image/Jpeg";
            context.Response.BinaryWrite(ms.GetBuffer());
 
            ms.Close();
            ms = null;
            image.Dispose();
            image = null;
        }
        #endregion
 
        #region 生成随机字符码
        public string CreateVerifyCode(int codeLen)
        {
            if (codeLen == 0)
            {
                codeLen = Length;
            }
 
            string[] arr = CodeSerial.Split(',');
 
            string code = "";
 
            int randValue = -1;
 
            Random rand = new Random(unchecked((int)DateTime.Now.Ticks));
 
            for (int i = 0; i < codeLen; i++)
            {
                randValue = rand.Next(0, arr.Length - 1);
 
                code += arr[randValue];
            }
 
            return code;
        }
        public string CreateVerifyCode()
        {
            return CreateVerifyCode(0);
        }
        #endregion
 
    }
}

为了向页面生成图片,我们新建一个ASP.NET一般处理程序ImageHandler.ashx,其代码如下:

using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.SessionState;
 
namespace verifycode_session
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class ImageHandler : IHttpHandler, IRequiresSessionState
    {
 
        public void ProcessRequest(HttpContext context)
        {
            string actionStr = context.Request["action"] == null ? string.Empty : context.Request["action"].ToLower();
            actionStr = actionStr.Split(new char[] { '?' })[0];
            if (actionStr == "getverifycode")   //getVerifyCode
            {
                VerifyCode v = new VerifyCode();
                string code = v.CreateVerifyCode();                //取随机码
                v.CreateImageOnPage(code, context);        // 输出图片
                context.Session.Remove("VERIFY_CODE");
                context.Session.Add("VERIFY_CODE", code.ToString());
            }
 
        }
 
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

最后我们把它输出在html页面上,并点击链接或图片可以换一张验证码图片,html代码如下:

<body>
    <div>
        <img src="/ImageHandler.ashx?action=getVerifyCode" onclick="this.src=this.src+'?'"
            alt="看不清换一张" id="VerfifyCodeImg" />
        <a href="javascript:void(0)" onclick="$('#VerfifyCodeImg').attr('src',$('#VerfifyCodeImg').attr('src')+'?')">
            看不清楚换一张</a>
    </div>
</body>

这里下载整个程序的demo