一、软件中使用验证码的作用
现在软件中的很多地方有用到验证码,比如注册账号、登录的时候等等。验证码的使用是为了防止“爆破”既暴力破解,那什么是暴力破解呢,暴力破解就是利用程序,按照一定的规律往表单中输入数据,逐个测试。验证码 是随机产生的同时它不仅仅是单纯的图片或数字,只有输入的验证码正确之后才会去后台数据库做验证,从而防止暴力破解。
二、示例讲解
创建一个ASP.NET程序,单独添加一个Web页面用于生成验证码,相关代码如下:
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Drawing;using System.IO;using System.Drawing.Imaging;namespace UI{ public partial class ValidateCodeCopy : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if(!IsPostBack) { //生成一个四位的随机码 string validateCode = RndNum(4); //将随机码保存到session中 Session["ValidateCode"] = validateCode; CreateImage(validateCode); } } ////// 生成一个随机码 /// /// 随机码的位数 ///public string RndNum(int VCodeNum ) { string VNUM = ""; string Vchar = "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[] VcArray = Vchar.Split(new char[]{ ','}); Random rd = new Random(); for (int i = 0; i <= VCodeNum - 1;i++) { int t = rd.Next(36); VNUM += VcArray[t]; } return VNUM; } /// /// 生成随机颜色 /// ///public Color GetRandomColor() { Random Rd_First = new Random((int)DateTime.Now.Ticks); Random Rd_Second = new Random((int)DateTime.Now.Ticks); //生成三个随机数 int red = Rd_First.Next(256); int Green = Rd_Second.Next(256); int blue = (red + Green) > 400 ? 0 : 400 - red + Green; blue = blue > 255 ? 255 : blue; return Color.FromArgb(red,Green, blue); } /// /// 将随机码绘制到图像,写入输出流 /// /// 随机码 public void CreateImage(string str_ValidateCode) { int int_imageWidth = str_ValidateCode.Length * 20; Bitmap thebitmap = new Bitmap(int_imageWidth,40); Random rd = new Random(); Graphics Gr = Graphics.FromImage(thebitmap); Gr.Clear(Color.White); Gr.DrawRectangle(new Pen(Color.LightGray, 1),0,0,int_imageWidth-1,39); Font font = new Font("Arial",16); for (int int_index = 0; int_index < str_ValidateCode.Length;int_index++ ) { string str_char = str_ValidateCode.Substring(int_index,1); Brush newBrush = new SolidBrush(GetRandomColor()); Point thePos = new Point(int_index * 20 + 1 + rd.Next(3), 3+ rd.Next(3)); Gr.DrawString(str_char, font, newBrush, thePos); } MemoryStream ms = new MemoryStream(); thebitmap.Save(ms, ImageFormat.Jpeg); Response.ClearContent(); Response.ContentType = "image/jpeg"; Response.BinaryWrite(ms.ToArray()); Gr.Dispose(); thebitmap.Dispose(); Response.End(); } }}
另外添加一张web页面 用于获取验证码,其前端HTML代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="UI.Test" %>
这样一个简单的验证码就实现了。
不积跬步无以至千里