c# 图形验证码生成 代码解析

之前做登录时,发送短信验证码需要做安全控制,使用到了图形验证码

使用的思路是:
1、建立一个验证码图片生成器页面
2、生成字母或数字组成的随机字符串
3、在Cookie中保存随机验证码
4、根据生成的随机验证码,生成验证码图片
5、前端调用该页面,填写验证码,后台获取用户输入的验证码与Session中保存的值比较,相同则验证通过

验证码生成器代码:

protected void Page_Load(object sender, EventArgs e)
{
    Response.Cache.SetNoStore();//禁用缓存
    CreateCheckCodeImage(GenerateCheckCode());

}
//生成数组和字母组合的随机字符串,并存入Session
private string GenerateCheckCode()
{
    //定义验证码长度
    int CODELENGTH = 4;
    int number;
    string RandomCode = string.Empty;
    Random r = new Random();
    for (int i = 0; i < CODELENGTH; i++)
    {
        number = r.Next();
        //字符从0~9, A~Z中随机产生,对应的ASCII码分别为48~57, 65~90 a-z 97~122
        number = number % 36;
        if (number < 10)
            number += 48;
        else
            number += 55;
        RandomCode += ((char)number).ToString();
    }
    //在Cookie中保存验证码
    Session["CheckCode"] = RandomCode;
    Response.Cookies.Add(new HttpCookie("CheckCode", RandomCode));
    return RandomCode;
}

//生成验证码图片
private void CreateCheckCodeImage(string checkCode)
{
    //若验证码为空,则直接返回
    if (checkCode == null || checkCode.Trim() == string.Empty)
        return;
    //根据验证码的长度确定输出图片的宽度
    int iWidth = (int)Math.Ceiling(checkCode.Length * 15m);
    int iHeight = 20;
    //创建图像
    Bitmap image = new Bitmap(iWidth, iHeight);
    //从图像获取一个绘图面
    Graphics g = Graphics.FromImage(image);

    try
    {
        Random r = new Random();
        //清空图片背景色
        g.Clear(Color.White);
        //画图片的背景噪音线10条
        for (int i = 0; i < 10; i++)
        {
            int x1 = r.Next(image.Width);
            int x2 = r.Next(image.Width);
            int y1 = r.Next(image.Height);
            int y2 = r.Next(image.Height);
            //用银色画出噪音线
            g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
        }
        //画图片的前景噪音点50个
        for (int i = 0; i < 50; i++)
        {
            int x = r.Next(image.Width);
            int y = r.Next(image.Height);
            image.SetPixel(x, y, Color.FromArgb(r.Next()));
        }
        //画图片的框线
        g.DrawRectangle(new Pen(Color.SaddleBrown), 0, 0, image.Width - 1, image.Height - 1);
        //定义绘制文字的字体
        Font f = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
        //线性渐变画刷
        System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.Purple, 1.2f, true);
        g.DrawString(checkCode, f, brush, 2, 2);
        //创建内存流用于输出图片
        using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
        {
            //图片格式制定为png
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            //清除缓冲区流中的所有输出
            Response.ClearContent();
            //输出流的HTTP MIME类型设置为"image/Png"
            Response.ContentType = "image/Png";
            //输出图片的二进制流
            Response.BinaryWrite(ms.ToArray());
        }
    }
    finally
    {
        //释放Bitmap对象和Graphics对象
        g.Dispose();
        image.Dispose();
    }
}

如果前端是以接口形式请求图形验证码,可以吧生成的图片转换成base64字符串形式返回给客户端,客户端通过设置 img的src=”data:image/png;base64,”+base64Str 来显示图形验证码

图片转base64编码:

//创建内存流用于输出图片
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
    //图片格式制定为png
    image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
    //清除缓冲区流中的所有输出
    Response.ClearContent();
    //输出流的HTTP MIME类型设置为"image/Png"
    Response.ContentType = "image/Png";
    //输出图片的二进制流
    Response.BinaryWrite(ms.ToArray());

    string base64Str = Convert.ToBase64String(ms.ToArray());
}

前端显示:

<img src="data:image/jpg;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAAAUCAYAAADRA14pAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAUoSURBVFhH5ZdbbBRVGMc/kvJEFAWioIJGH7CiVUQ2RhBvQSYFmmJEhVYU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nOI21HksKr7RO6ZheXTGIL2z38AYihA8jL4lNweer5uV1Sfgh2s/CNRhtnlQdvI14TAibHfzsFq4L4SZsMXZhAu1ELgsFrHIpLPJXYh/hly6ES1AcMYZp/RZgBSnhjJHq8BQitAIiiStsW2dwkxA2utF/6AAdjc25N1Ie0VW+uR0ztPB7evB+q04Kz7W6pfA8Fn6afsF4+hmGcZTn8gzn7w4W9uEHLddm7cJUIWwcRlCFHGrNPF4xLGzs5y0vOpHScYV9ZqcUHmT26EgszuBtapSb1nItV2nWqRk2gs4naa+5Vwq/z318hT7+pvrwDJVJYTG7QDtW82FjMr+kX+UdQI25RQmbfh1R1Jpf4jVSwvl873PVmzN1Uy/c0nGERf524mb+HE22/tGx2FSYjfLQcR+fsu6ng0ijOt6w6lHgLMNuFBpCuAHV8rqDZ9+rhD1lPLuMtxYThbDRCJXBAaylLXiBiuQpazqfsrJpE6+cjXiVlPAK67TsmSyxhWX+nub87Uwqf9Wm5RZuRqVukdgBPiTsxRijFWquOrBKCy+wzspZEAcPIbyIU0liN/BL3xxDuBy1qtdlEWeGr5ySmaNn6er/SnDjGvlPjptrIny1KUwvm6er/xlH+PopA/Evy3vMc/0rY8gAAAAASUVORK5CYII=" />

这里写图片描述

另外还有一种思路是:
1、客户端请求图形验证码
2、服务器向客户端返回base64形式的图片,并且返回加密过的后台生成的验证码(可以使用base64加密或其他加密方法)
3、客户端解密验证码和用户输入的验证码比较(或者加密用户输入验证码和获取的加密验证码比较),这样可以实现在客户端完成验证

你可能感兴趣的:(c#,图形验证码,c#)