asp. net Method of Generating Verification Code (I)

  • 2021-07-18 08:49:46
  • OfStack

At present, many websites have registration and login pages. In order to better meet the user experience and website security, many websites use dynamically generated graphic codes or additional codes for verification. The following methods for generating verification codes are sorted out as follows.

The realization of authentication technology is to generate a random number on the server side, save it in memory, send it to the browser, and submit it to the user in the form of pictures. In the process of doing the project, when I completed a verification code for user registration and login using script, I found that there are various ways to generate verification codes. The following are mainly several different ways to generate verification codes:

1. Draw a pure digital website verification code

This example realizes the digital verification code technology, that is, randomly generating 4 digits as verification codes. Digital verification code technology can be used when developing and drawing member login verification module.

Design process

Write the method of generating digital verification code in a newly created form 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
 {
 // Generate random generator  
 Random random = new Random();
 // Clear the background color of the picture  
 g.Clear(Color.White);
 // Draw the background noise line of the picture  
 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);
 // Noise points in the foreground of drawing pictures  
 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()));
 }
 // Draw the border line of the picture  
 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();
 }
 } 

Then call CreateCheckCodeImage () in Page_Load:


protected void Page_Load(object sender, EventArgs e)
 {
 this.CreateCheckCodeImage(RndNum()); 
}
 Then in the window where we log in, we can use simple controls: 
<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=" Can't see clearly? Click on the picture to change 1 A " Height="16px" 
 Font-Size="Small" ForeColor="Red"></asp:Label>
 <br />
 <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
 In Button1_Click Judge the correctness of the verification code input in: 
protected void Button1_Click(object sender, EventArgs e)
{
 if (String.Compare(Request.Cookies["yzmcode"].Value, TextBox1.Text, true) != 0)
 {
 Response.Write("<script>alert(' Verification code error! ')</script>");
 }
 else
 Response.Write("<script>alert(' Verification code is correct! ')</script>");
}

2. Draw the website verification code of the combination of numbers and letters

It is very similar to pure numbers, but the specific difference is in the method of randomly generating strings


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;
 }

After the string is generated, the next step is to draw the string as a picture and display it. The code is as follows:


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
 {
 // Generate random generator 
 Random random = new Random();
 // Clear the background color of the picture 
 g.Clear(Color.White);
 // Draw the background noise line of the picture 
 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);
 // Noise points in the foreground of drawing pictures 
 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()));
 }
 // Draw the border line of the picture 
 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();
 }
 } 

Judge whether the verification code input is correct in the login window:


protected void Button1_Click(object sender, EventArgs e)
 {
 HttpCookie cookie = Request.Cookies["CheckCode"];
 if (cookie.Value == this.TextBox1.Text.Trim())
 {
 Response.Write("<script>alert(' Verification code is correct! ')</script>");
 }
 else
 {
 Response.Write("<script>alert(' Verification code error! ')</script>"); 
 }
 }

Then the website verification code with the combination of numbers and letters is generated.

Verification code of 3, 4 expressions

Other verification codes are similar to those generated by mixing numbers and letters, so I won't write them. The specific difference is in the method of randomly generating 4 expressions, as follows:


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;
}

This article mainly introduces three methods to generate verification code, and I hope everyone likes it.


Related articles: