ASP.NET graphical verification code generation practice

Hello World!
Release: 2020-04-28 13:18:07
Original
2372 people have browsed it

Why use graphical verification code

In order to prevent attackers from writing programs to repeatedly submit forms and causing trouble for other users and website operations, it is generally necessary to use graphical verification before submitting the form. Code is verified to confirm that the submission operation is a human operation and not a machine batch operation.

Principle Analysis

When generating graphic verification codes, two technologies are mainly used:

1. Generate random Numbers or letters

2. Convert the generated random numbers or random letters into image format and add noise to the image and display it.

Generation method:

1. Front-end control code

<asp:TextBox ID="txtValidateNum" runat="server" Width="98px"></asp:TextBox>
<asp:Image ID="Image1" runat="server" Height="22px" Width="58px" ImageUrl="~ValidateNum.aspx"/>请输入图片中验证码!
Copy after login

2. ValidateNum.aspx page processing steps

(1) Randomly generate a random string of length N. The value of N can be set by the developer. The string contains numbers, letters, etc.

(2) Create a randomly generated string into a picture and display it.

(3) Save the verification code

First create a CreateRandomNum(int n) method in the ValidateNum .aspx.cs file to randomly generate a random string of length n. In order to avoid generating repeated random numbers, the random number results will be recorded through variables. If the same value appears in the last random number, the method itself will be called to ensure that different random numbers are generated. The code is as follows:

//生成随机字符串
private string CreateRandomNum (int n)
{
    string allChar = "0,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";
    string[] allCharArray = allChar.Split(&#39;,&#39;);//拆分成数组
    string randomNum = "";
    int temp = 1;
    Random rand = new Random();
    for(int i = 0;i < n;i++)
    {
        if(temp != -1)
        {
            rand = new Random(i * temp *((int)DateTime.Now.Ticks));
        }
        int t = rand.Next(35);
        if(temp == t)
        {
            return CreateRandomNum(n);
        }
        temp = t;
        randomNum += allCharArray[i];
    }
    return randomNum;
}
Copy after login

Then create the CreateImage(string validateNum) method based on the generated random string to further generate a graphic code. In order to further ensure security, add some interference colors to the graphic verification code, such as random background patterns, Word processing, etc. The code is as follows:

//生成图片
private void CreateImage(string validateNum)
{
    if(validateNum == null || validateNum.Trim() == String.Empty)
        return;
    //生成Bitmap图像
    System.Drawing.Bitmap image = new System.Drawing.Bitmap(validateNum.Length * 12 + 10,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(validateNum,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();
    }
}
Copy after login

Finally, in the page loading event Page_Load, create and display the image of the verification code string, and save the verification string in the Session.

protected void Page_Load(object sender,EventArgs e)
{
    if(!IsPostBack)
    {
        string validateNum = CreateRandomNum(4);//生成4位随机字符串
        CreateImage(validateNum);//将随机字符串绘制成图片
        Session["ValidateNum"] = validateNum;  //将随机字符串保存在Session中
    }
}
Copy after login

At this point, a simple image verification code generation algorithm has been written. Of course, you can add richer security settings on this basis, such as Session expiration time, etc.

The above is the detailed content of ASP.NET graphical verification code generation practice. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template