MVC5 using Geetest Verification code example

Source: Internet
Author: User
Models folder entity class

LoginInfo.cs

Using System;
Using System.Collections.Generic;
Using System.ComponentModel.DataAnnotations;
Using System.Linq;
Using System.Web;

Namespace MvcDemo.Models.Geetest
{public
    class Logininfo
    {
        [Required (errormessage= "User name cannot be empty"] Public
        string UserName {get; set;}

        [Required (errormessage = "Password cannot be blank")]
        public string Password {get; set;}}}

GeetestConfig.cs

Using System;

Namespace MvcDemo.Models.Geetest
{public
    class Geetestconfig
    {
        ///<summary>
        /// Verify ID
        ///</summary> public
        const string publickey = "6ef7c61ac11117de6996efa65be1c27e";

        <summary>
        ///Verify key
        ///</summary> public
        const string Privatekey = " 62add4e324dd9e9ef2ea35192f8d9181 ";
    }
}

GeetestLib.cs

Using System;
Using System.Collections;
Using System.Collections.Generic;
Using System.IO;
Using System.Linq;
Using System.Net;
Using System.Security.Cryptography;

Using System.Text;
    namespace MvcDemo.Models.Geetest {///<summary>///geetestlib validation C # SDK Basic Library///</summary> public class Geetestlib {///<summary>///SDK version number///</summary> p

        Ublic Const string Version = "3.1.1";

        <summary>///SDK Development language///</summary> Public const string Sdklang = "CSharp"; <summary>///Validation API URL///</summary> protected const string Apiur

        L = "http://api.geetest.com";  <summary>///Register URL///</summary> protected const string Registerurl =

        "/register.php"; <summary>///Validate URL///</summary> protected const string validateurl = "/validate.php"; <summary>///Verification API Service status session Key///</summary> Public const string Gtserv

        Erstatussessionkey = "Gt_server_status"; <summary>///Validation form data chllenge///</summary> Public const string Fngeete two times

        Stchallenge = "Geetest_challenge"; <summary>///Validation form data Validate///</summary> Public const string Fngeete two times

        Stvalidate = "Geetest_validate"; <summary>///Validation form data seccode///</summary> Public const string Fngeetes two times

        Tseccode = "Geetest_seccode";

        <summary>///Validation Success result string///</summary> public const int successresult = 1; 

        <summary>///Failure test string///</summary> Public const int failresult = 0; <summary>/Decision for robot result string///</summary> Public const string forbiddenresult = "forbidden";
        Private readonly string captchaid = "";
        Private readonly string privatekey = "";

        private string responsestr = ""; <summary>///Geetestlib Constructor///</summary>///<param name= "PublicKey" > Verification of the public key </param>///<param name= "Privatekey" > polarography verify the Private key </param> the Geetestlib (string publ
            Ickey, String privatekey) {This.privatekey = Privatekey;
        Captchaid = PublicKey;
            private int Getrandomnum () {var rand = new Random (); var randres = rand.
            Next (100);
        return randres; ///<summary>///Validation initialization preprocessing///</summary>///<returns> Initialization Results </
     Returns> public byte preprocess () {if (Captchaid = null)       {Console.WriteLine ("PublicKey is null!");
                else {var challenge = Registerchallenge (); if (challenge.
                    Length = =) {getsuccesspreprocessres (challenge);
                return 1;
                } getfailpreprocessres ();
            Console.WriteLine ("Server regist Challenge failed!");
        return 0;
        public string Getresponsestr () {return responsestr; ///<summary>///After preprocessing failed return format string///</summary> private void Getfailprepr
            Ocessres () {var rand1 = Getrandomnum ();
            var rand2 = Getrandomnum ();
            var md5str1 = Md5encode (Rand1 + "");
            var md5str2 = Md5encode (Rand2 + "");
            var challenge = md5str1 + md5str2.substring (0, 2); Responsestr = "{" + string.Format ("\ Success\": {0},\ "gt\": \ "{1}\", \ "challenge\": \ "{2}\" ", 0, Captchaid, challenge) +"} "; Standard string///</summary> private void Getsuccessprep after successful///<summary>///preprocessing
            Rocessres (String challenge) {challenge = Md5encode (challenge + privatekey); Responsestr = "{" + string.
        Format ("\ Success\": {0},\ "gt\": \ "{1}\", \ "challenge\": \ "{2}\" ", 1, Captchaid, Challenge) +"} "; }///<summary>///failback mode validation///</summary>///<param name= "ch Allenge ">failback mode is used to decode the answers together with validate, to determine if validation is correct </param>///<param name=" Validate ">failback mode for use with CH
        Allenge together to decode the answer, to determine whether the correctness of validation </param>///<param name= "Seccode" >failback mode, is actually a useless parameter </param> <returns> validation Results </returns> public int failbackvalidaterequest (String challenge, string validate, Stri Ng Seccode) {if (! RequestisLegal (Challenge, validate, Seccode)) return failresult; var validatestr = validate.
            Split ('_');
            var Encodeans = validatestr[0];
            var encodefullbgimgindex = validatestr[1];
            var encodeimggrpindex = validatestr[2];
            var Decodeans = decoderesponse (challenge, Encodeans);
            var decodefullbgimgindex = decoderesponse (challenge, Encodefullbgimgindex);
            var decodeimggrpindex = decoderesponse (challenge, Encodeimggrpindex);
            var validateresult = Validatefailimage (Decodeans, Decodefullbgimgindex, Decodeimggrpindex);
        return validateresult; private int Validatefailimage (int ans, int full_bg_index, int img_grp_index) {const int th
            Read = 3; var fullbgname = Md5encode (Full_bg_index + "").
            Substring (0, 10); var bgname = Md5encode (Img_grp_index + "").
            Substring (10, 10);
            var answerdecode = ""; for (var i = 0; i < 9; i++{switch (i% 2) {case 0:answe
                        Rdecode + + fullbgname.elementat (i);
                    Break
                        Case 1:answerdecode + + bgname.elementat (i);
                Break
            } var Xdecode = answerdecode.substring (4);
            var xint = Convert.ToInt32 (Xdecode, 16);
            var result = xint% 200;
            if (Result <) result = 40; Return Math.Abs (Ans-result) < thread?
        Successresult:failresult; private bool Requestislegal (String challenge, String validate, String seccode) {return!ch Allenge. Equals (String. Empty) &&!validate. Equals (String. Empty) &&!seccode. Equals (String.
        Empty); }///<summary>///to gt-server two validation///</summary>///<param name= "c Hallenge ">Unique identification of the secondary authentication session </param>///<param name= "Validate" > The validation result identification string returned by the server side after drag completion </param>///<p Aram Name= "Seccode" > Verify the result of the check code, if Gt-server return is not equal to this value indicates validation failure </param>///<returns> two verification results </returns&
        Gt public int Enhencedvalidaterequest (String challenge, String validate, String seccode) {if (!
            Requestislegal (Challenge, validate, Seccode)) return failresult; if (validate. Length <= 0 | | !
            Checkresultbyprivate (Challenge, validate)) return failresult;
            var query = "Seccode=" + Seccode + "&sdk=csharp_" + Version;
            var response = "";
            try {response = postvalidate (query);
            catch (Exception e) {Console.WriteLine (e); return response. Equals (Md5encode (Seccode))?
        Successresult:failresult;
   private string Readcontentfromget (string url) {         try {var request = (HttpWebRequest) webrequest.create (URL); Request.
                Timeout = 20000; var response = (HttpWebResponse) request.
                GetResponse (); var Myresponsestream = response.
                GetResponseStream ();
                var mystreamreader = new StreamReader (Myresponsestream, encoding.getencoding ("Utf-8"));
                var retstring = Mystreamreader.readtoend ();
                Mystreamreader.close ();
                Myresponsestream.close ();
            return retstring;
            Catch {return ""; }} private String Registerchallenge () {var url = string.
            Format ("{0}{1}?gt={2}", Apiurl, Registerurl, Captchaid);
            var retstring = readcontentfromget (URL);
        return retstring; private bool Checkresultbyprivate (string origin, String validate) {var encodestr = Md5encode (Privatekey + "geetest" + origin); return validate.
        Equals (ENCODESTR); private string Postvalidate (string data) {var url = string.
            Format ("{0}{1}", Apiurl, Validateurl);
            var request = (HttpWebRequest) webrequest.create (URL); Request.
            method = "POST"; Request.
            ContentType = "application/x-www-form-urlencoded"; Request.
            ContentLength = Encoding.UTF8.GetByteCount (data); Send data var myrequeststream = Request.
            GetRequestStream ();
            var requestbytes = Encoding.ASCII.GetBytes (data);
            Myrequeststream.write (requestbytes, 0, requestbytes.length);

            Myrequeststream.close (); var response = (HttpWebResponse) request.
            GetResponse (); Read return information var Myresponsestream = response.
            GetResponseStream ();
            var mystreamreader = new StreamReader (Myresponsestream, encoding.getencoding ("Utf-8")); var retstring = Mystreamreader.readtoend ();
            Mystreamreader.close ();

            Myresponsestream.close ();
        return retstring; private int Decoderandbase (String challenge) {var basestr = challenge.
            Substring (32, 2);
            var templist = new list<int> ();
                for (var i = 0; i < basestr.length i++) {var tempascii = (int) basestr[i]; Templist.add (Tempascii > 57)?
            (tempAscii-87): (tempAscii-48));
            var result = Templist.elementat (0) * + templist.elementat (1);
        return result; private int Decoderesponse (String challenge, String str) {if (str).
            Length >) return 0;
            var Shuzi = new[] {1, 2, 5, 10, 50};
            var chongfu = "";
            var key = new Hashtable ();
            var count = 0; for (var i = 0; I &lT Challenge. Length; i++) {var item = Challenge.
                ElementAt (i) + ""; if (Chongfu.
                Contains (item)) continue;
                var value = shuzi[count% 5];
                Chongfu + = Item;
                count++; Key.
            ADD (item, value);
             var res = 0;

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.