WebSite---Front desk system picture Verification Code experience

Source: Internet
Author: User
Tags pkcs7

Background: Because the mobile app and Msite mobile phone registration to send SMS verification code does not add the image verification code function. The company's SMS interface was maliciously brushed. So we feel like adding an image verification code function on the mobile side. Share a general idea of how to achieve it. PS demo is written by itself. There is a big gap with the company code.

I. Photo Verification Code First edition

1. Establish the image verification code Validationcodehelper

1.1 Fill out the method to generate the corresponding. CAPTCHA: default is 4 digits

1         private static char[] _constant = {   2 ' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ',         ' 9 ',   3         ' 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 ',    4         ' 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 '    5          }; 6  7 public         static string Createvalidatecode (int length = 4, bool Isnum = true) 8         {9             var sb = new String Builder ();             var constant = isnum? _constant. Take (10). ToArray (): _constant;11             var constant_count = constant. Count (),             random rd = new random (), 0 for             (var index =; index < length; index++)                 Append (constant[rd. Next (Constant_count)]);             }17             return sb. ToString ();         

1.2 The image stream is generated from the verification code, which is copied from other bloggers. I'm not good at pictures.

 1 public static byte[] GetImage (string code) 2 {3 Bitmap image = new Bitmap ((int) math.ceiling (code.l Ength * 16.0), 27); 4 Graphics g = graphics.fromimage (image);                  5 Try 6 {7 random random = new Random (); 8 g.clear (Color.gray); 9 for (int i = 0; i <; i++) {one 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, x2, y1, y2),}17 Fo NT Font = new Font ("Arial", FontStyle.Bold | fontstyle.italic) LinearGradientBrush brush = new LinearGradientBrush (new Rectangle (0, 0, image). Width, image. Height), Color.Blue, color.darkred, 1.2f, True); g.drawstring (code, font, Brush, 3, 2); (int i = 0; i <; i++) {x int × = random . Next (image. Width), and the int y = random. Next (image. Height), image. SetPixel (x, Y, Color.FromArgb (random. Next ()));}26 G.drawrectangle (New Pen (Color.silver), 0, 0, image. Width-1, image. Height-1); MemoryStream stream = new MemoryStream (); Save (stream, imageformat.jpeg); return stream.             ToArray ();}31 catch (Exception ex) + {return null;34 }35 finally36 {PNS g.dispose (); Dispose (); 39}40}

2. Encapsulating a simple cookiehelper type is primarily to encrypt cookies. Simply encapsulated, no generics are added to Cookiehelper, and object handling is not supported. The Cookiehelper library inside the company is more powerful. But you can't share the code. So I wrote a simple one.

 1 public class Cookiehelper 2 {3 4 #region string encryption decrypt 5 6 private static string _md5 = "8ff0c65d- a2ed-4e1e-af85-690c08b8d039 "; 7 8 private static string Decrypt (String cipherstring) 9 {byte[] keyarray;11 b yte[] Toencryptarray = convert.frombase64string (cipherstring); MD5CryptoServiceProvider hashmd5 = new MD5Cry Ptoserviceprovider (); Keyarray = Hashmd5. ComputeHash (UTF8Encoding.UTF8.GetBytes (_MD5)); hashmd5. Clear (); TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider (); tdes.k EY = keyarray;18 tdes. Mode = ciphermode.ecb;19 tdes. Padding = paddingmode.pkcs7;20 ICryptoTransform ctransform = tdes. CreateDecryptor (); byte[] Resultarray = Ctransform.transformfinalblock (              Oencryptarray, 0, toencryptarray.length); Tdes. Clear (); UTF8Encoding.UTF8.GetString return (resultarray),}26 private static string Encrypt (St Ring Toencrypt) (byte[] keyarray;30 byte[] Toencryptarray = UTF8Encoding.UTF8.GetByte S (toencrypt), MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider (), Keyarray = ha Shmd5. ComputeHash (UTF8Encoding.UTF8.GetBytes (_MD5)); hashmd5. Clear (); TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider (); tdes.k EY = keyarray;37 tdes. Mode = ciphermode.ecb;38 tdes. Padding = paddingmode.pkcs7;39 ICryptoTransform ctransform = tdes.               CreateEncryptor (); byte[] Resultarray =42 ctransform.transformfinalblock (Toencryptarray, 0,43 toencryptarray.length); Tdes. Clear (); return convert.tobase64string (resultarray, 0, resultarray.length); 46}#endregion50 #region Cookie53 public static void Savecookie (string name, string value, int expiredsecond = 0) @ $ var encryptstr = Encrypt (value); var collection = Ht tpcontext.current.response.cookies;58 collection. ADD (name) HttpCookie {Value = encryptstr,61 Expires = expiredsecond & Gt 0?  System.DateTime.Now.AddSeconds (Expiredsecond): System.DateTime.MaxValue62});}64 static string GetCookie (string name) * * * var cookie = HttpContext.Current.Request.Cookies.Get (name)             ; if (cookie = null) null;71}72 else73 {Decrypt return (cookie). Value);}76}77 #endregion79}

3. Controller added Image service. Setting a cookie for a picture is valid for one minute

 1 public class Homecontroller:controller 2 {3 public actionresult Index () 4 {5 return View (); 6} 7 8 public Filecontentresult Imagevalidator () 9 {ten var code = Validationcodehelp Er. Createvalidatecode (); Cookiehelper.savecookie ("Piccode", Code,); var picbyte = Validationco Dehelper.getimage (code); return File (Picbyte, "image/jpeg"); }15//<summary>17///Check the image verification code is correct///</summary>19///<p Aram Name= "Code" &GT;&LT;/PARAM&GT;20//<returns></returns>21 public ActionResult Checkpiccod E (String code): {cookiecode var = cookiehelper.getcookie ("Piccode");             Isnullorwhitespace (Cookiecode)) ("Verification Code expires", Jsonrequestbehavior.allowget), 27 }28 if (code. Trim (). ToUpper () = = CookiecoDe.             ToUpper ()) {return Json ("Captcha correct", jsonrequestbehavior.allowget); 31}32 else33 {return Json ("Captcha error", Jsonrequestbehavior.allowget), 35}36}3 7}

4. Front page. Click to refresh the image by modifying the SRC link of img.

 1 

5. The first version of the Basic code implementation, click on the image to refresh the verification code, the image verification code is valid for one minute.

In a minute.

A minute later, the verification code expired.

6. We look at the above two pictures to verify that the code is OK. Do. Normal website use is OK. Because we set the validity time of the verification code to be one minute. Let's look at the effect inside the fiddler.

The cookie expires when my face is simulated in the fiddler. That is, if the client user crawls the Piccode cookie. Build your own request. Cookies are not invalidated.

Two. Image Verification code revision.

It is not possible to set the cookie's expiration time directly from above. Then we can only modify it on the cookie store value. Let's see how our code is implemented. We store the ticks and captcha strings of the expiration time in a cookie.

///&LT;SUMMARY&GT;15///Build a picture cookie string, code and expiry time separated by commas//&LT;/SUMMARY&GT;17 Pub Lic static string Buildvalidatecodestorage (string code, int expiredseconds =), {STRING.F Ormat ("{0},{1}", Code, System.DateTime.Now.AddSeconds (expiredseconds).         Ticks);}21//<summary>23///parsing image Verification Code COOKIE24//&LT;/SUMMARY&GT;25 public static string Anysisvalidatecode (String codestorage) (string).             Isnullorwhitespace (Codestorage)) {null;30}31 else32 {vals var = codestorage.split (', '); Vals.                 Count ()! = 2) {null;37 return}38 Else39 {ticks = 0;41 long. TryParse (Vals[1], out ticks);KS > System.DateTime.Now.Ticks), {vals[0];45 return                 }46 else47 {null;49}50 }51}52}

Three. Summary

This is what we think of the Image Verification Code implementation scheme. I do not know how other Bo friends to achieve the company. I hope you can share it.

Http://files.cnblogs.com/files/FourLeafCloverZc/CSharp.zip

WebSite---Front desk system picture Verification Code experience

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.