Generate random verification code for user login system

Source: Internet
Author: User
Tags random seed

C#

Randomly generated code class: Validatecode.ashx

<%@ WebHandler language= "C #" class= "Validatecode"%> using System; Using System.Web; Using System.Drawing; Using System.Web.SessionState; To use a session in a generic handler, you must implement an interface public class Validatecode:ihttphandler,irequiressessionstate {

    public void ProcessRequest (HttpContext context)     {         context. Response.ContentType = "Image/jpeg";         String code = GETRNDSTR (); //Generate 4 random characters                 //record generated verification code          context. session["Code" = code;         using (Bitmap img = createimages (Code, "ch"))          {            img. Save (context. Response.outputstream, System.Drawing.Imaging.ImageFormat.Jpeg);        }    }

    public bool isreusable     {        get  & nbsp;      {            return False        }    }    //<summary>     ///digital random number    //</summary>    //<returns></returns>  & nbsp;  private String Getrndnum ()     {        String code = String. Empty;         random random = new random ();         for (int i = 0; i < 4; i++)         {&NB sp;           code + = random. Next (9);        }         return code;   &nbsp }    ///<summary>    ///  English random    //</summary>    //<returns></returns>     private String getrndstr ()      {        String vchar = "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 (', ');         string checkcode = string. Empty;         Random rand = new Random ();         for (int i = 0; i < 4; i++)         {&NB sp;           int t = rand. Next (vcarray.length);             Checkcode + = vcarray[t];        }         return Checkcode;    }    //<summary>    //Chinese random    ///</ Summary>    ///<returns></returns>     private String getrndch ()      {        System.Text.Encoding GB = system.text.encoding.default;// Get GB2312 Encoding page (table)         object[] bytes = Createregioncode (4);//Born 4 random Chinese Chinese character coding          string[] str = new STRING[4];         System.Text.StringBuilder sb = new System.Text.StringBuilder ();         for (int i = 0; i < 4; i++)         {&NB sp;          //decoding Chinese characters according to Chinese character coding byte array              Str[i] = GB. GetString ((byte[]) Convert.changetype (Bytes[i], typeof (byte[)));             sb. Append (Str[i]. ToString ());        }         return sb. ToString ();    }    //<summary>    //Generate random Chinese characters    //</ Summary>    //<param name= "strlength" ></param>    //<returns ></returns>     private static object[] Createregioncode (int strlength)     {& nbsp;      //define a string array to store the constituent elements of the Chinese character coding         string[] RBase = new String[16] {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "B", "C", "D", "E", "F"};         random rnd = new Random ();         object[] bytes = new Object[strlength];

        for (int i = 0; i < strlength; i++)       & nbsp {           //Location code 1th bit              int r1 = rnd. Next (11, 14);             string str_r1 = Rbase[r1]. Trim ();            //Location Code 2nd digit              rnd = new Random (R1 * Unchecked ((int) DateTime.Now.Ticks) + i);             int R2;             if (r1 = =)              {                 r2 = rnd. Next (0, 7);            }             Else              {                 r2 = rnd. Next (0, 16);            }              string str_r2 = Rbase[r2]. Trim ();

           //Location Code 3rd bit              rnd = new Random (R2 * Unchecked ((int) DateTime.Now.Ticks) + i);//replace random seed              int r3 = rnd. Next (10, 16);             string str_r3 = Rbase[r3]. Trim ();

           //Location Code 4th digit              rnd = new Random (R3 * Unchecked ((int) DateTime.Now.Ticks) + i);             int R4;             if (r3 = = Ten)              {                 R4 = rnd. Next (1, 16);            }              else if (r3 = =)             {                 R4 = rnd. Next (0, 15);            }              Else             {                 R4 = rnd. Next (0, 16);            }              string str_r4 = Rbase[r4]. Trim ();            //Define two-byte variable storage generated random Chinese character location codes              byte byte1 = convert.tobyte (str_r1 + str_r2, 16);             byte Byte2 = convert.tobyte (Str_r3 + STR_R4, 16);

           //Storing two byte variables in a byte array              byte[] Str_r = new byte[] {byte1, byte2};

           //will produce a byte array of a Chinese character into the object array              bytes. SetValue (Str_r, i);        }         return bytes;    }    //<summary>    //Picture background + interference line    /// Lt;/summary>    //<param name= "Checkcode" ></param>    //< returns></returns>     Private Bitmap createimages (string checkcode, String type)      {        int step = 0;         if (type = = "ch")         {             Step = 5;//Chinese characters, boundary value bigger        }         int iwidth = (int) (Checkcode.length * (+ step));         System.Drawing.Bitmap image = new System.Drawing.Bitmap (iwidth, 33);         Graphics g = graphics.fromimage (image);         g.clear (Color.White);//clear background color          color[] C = {color.black, color.red, Color.darkblue, Color.green, Color.orange, Color.brown, Color.darkcyan, Color . Purple};//define random colors         string[] Font = {"Verdana", "Microsoft Sans Serif", "Comic S Ans MS "," Arial "," Song Body "};         Random rand = new Random ();

        for (int i = 0; i < i++)         {            int x1 = rand. Next (image. Width);             int x2 = rand. Next (image. Width);             int y1 = rand. Next (image. Height);             int y2 = rand. Next (image. Height);             G.drawline (New Pen (Color.lightgray, 1), X1, Y1, x2, y2);//Draw line        } by coordinates

        for (int i = 0; i < checkcode.length; i++)     & nbsp;   {            int cindex = rand. Next (7);             int findex = rand. Next (5);

            Font f = new System.Drawing.Font (Font[findex] , System.Drawing.FontStyle.Bold);             Brush B = new System.Drawing.SolidBrush (c[cindex ]);             int II = 4;             if ((i + 1)% 2 = = 0)              {                 II = 2;            }              g.drawstring (Checkcode.substring (i, 1), F, B, 3 + (I * (+ + Step)), ii);

} g.drawrectangle (New Pen (Color.Black, 0), 0, 0, image. Width-1, image.         HEIGHT-1);         System.IO.MemoryStream ms = new System.IO.MemoryStream ();     return image; } }

Page Call:

<tr>
<td> captcha: </td><td><input type= "text" id= "Txtcode" runat= "Server"/></td><td>
<br/></td>
</tr>

Generate random verification code for user login system

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.