技术开发 频道

ASP.NET2.0生成验证码(防一个session时间内攻击)


【IT168技术文档】

1 private void Page_Load(object sender, System.EventArgs e) 2 { 3 this.CreateCheckCodeImage(GenerateCheckCode()); 4 } 5 6 #region 生成4位随机数 7 private string GenerateCheckCode() 8 { 9 int number; 10 char code; 11 string checkCode = String.Empty; 12 System.Random random = new Random(); 13 for(int i=0; i<4; i++) 14 { 15 number = random.Next(); 16 17 if(number % 2 == 0) 18 { 19 code = (char)('0' + (char)(number % 10)); 20 } 21 else 22 { 23 code = (char)('A' + (char)(number % 26)); 24 } 25 26 code = (char)('0' + (char)(number % 10)); 27 28 checkCode += code.ToString(); 29 } 30 HttpContext.Current.Session["CheckCode"]=checkCode; 31 return checkCode; 32 } 33 #endregion 34 35 #region 生成验证码图片 36 private void CreateCheckCodeImage(string checkCode) 37 { 38 if(checkCode == null || checkCode.Trim() == String.Empty) 39 { 40 return; 41 } 42 Bitmap image = new Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22); 43 Graphics g = Graphics.FromImage(image); 44 try 45 { 46 //生成随机生成器 47 Random random = new Random(); 48 49 //清空图片背景色 50 g.Clear(Color.White); 51 52 //画图片的背景噪音线 53 for(int i=0; i<25; i++) 54 { 55 int x1 = random.Next(image.Width); 56 int x2 = random.Next(image.Width); 57 int y1 = random.Next(image.Height); 58 int y2 = random.Next(image.Height); 59 60 g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); 61 } 62 63 Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic)); 64 LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true); 65 g.DrawString(checkCode, font, brush, 2, 2); 66 67 //画图片的前景噪音点 68 for(int i=0; i<100; i++) 69 { 70 int x = random.Next(image.Width); 71 int y = random.Next(image.Height); 72 73 image.SetPixel(x, y, Color.FromArgb(random.Next())); 74 } 75 76 //画图片的边框线 77 g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); 78 MemoryStream ms = new MemoryStream(); 79 image.Save(ms,ImageFormat.Gif); 80 Response.ClearContent(); 81 Response.ContentType = "image/Gif"; 82 Response.BinaryWrite(ms.ToArray()); 83 } 84 finally 85 { 86 g.Dispose(); 87 image.Dispose(); 88 } 89 } 90 #endregion 91 92 public static bool CheckCode(string strCode) 93 { 94 strCode = strCode.ToUpper(); 95 string strSessionCode = HttpContext.Current.Session["CheckCode"] + ""; 96 strSessionCode = strSessionCode.ToUpper(); 97 System.Web.HttpContext.Current.Session["CheckCode"] = null;//注意要清空,防止一个session时间内攻击 98 return (strSessionCode == strCode); 99 }
0
相关文章