asp.net mvc combining JavaScript login, checksum encryption _ Practical Tips

Source: Internet
Author: User
Tags datetime decrypt md5 md5 encryption sha1

Recently have nothing to write their own family financial revenue and expenditure management system, also includes expenditure management, revenue management and some statistical functions.

First, the login module, because it involves get and post requests, these things can be monitored and crawled, so consider this use RSA encryption and decryption method to transmit user name and password parameters, page js as follows:

/* need to introduce three JS files, Bigint.js, rsa.js and barrett.js, use cookies need to introduce jquery.cookie.js file////background interaction to get public key function Getpublickey () {
  var pubkey = '; if ($.cookie (' publickey ') = null) {$.ajax ({url: "/account/getrsapublickey", type: "Get", Contentt ype: "application/x-www-form-urlencoded; Charset=utf-8 ", Async:false, data: {}, DataType:" JSON ", success:function (data) {if (d Ata. Code = = 0) {PubKey = data. Rsapublickey + "," + data.
          Key;
        $.cookie (' PublicKey ', PubKey, {expires:1/1440});
        else {Config.Method.JudgeCode (data, 1);
  }
      }
    });
  else {PubKey = $.cookie (' PublicKey ');
return PubKey;
  }//Public key encrypts user password PWD for RSA encrypted parameter function Rsaencrypt (pwd) {var publickey = Getpublickey ();
  Setmaxdigits (129);
  var rsakey = new Rsakeypair (Publickey.split (",") [0], "", Publickey.split (",") [1]);
  var pwdrtn = encryptedstring (Rsakey, PWD);
return Pwdrtn + "," + Publickey.split (",") [2]; }
//post login request, parameter <script type= "Text/javascript" > $ (Function () {$ (' #btnSubmit '). Live (' click ', function () {
      var uName = $ (' #u '). Val ();
      var pwd = $ (' #p '). Val ();
        if (UName = = "") {alert (' User name cannot be empty ');
      Return
        } if (pwd = = "") {alert (' User password cannot be empty ');
      Return
      var enpwd = Rsaencrypt (pwd); $.ajax {type: POST, url: "/account/userlogin", data: {' UserName ': uName, ' Pwd ': Enpwd.split (", ") [0], ' Key ': Enpwd.split (", ") [1], ' Rurl ': $ (' #hiddenUrl '). Val ()}, ContentType:" Application/x-www-form-urlencode D Charset=utf-8 ", Async:false, DataType:" JSON ", success:function (data) {if (Data.resu
            lt = = true) {window.location.href = Data.url;
          return false;
          else {$ (' #msg '). Text (data.message); }, Error:function (XMLHttpRequest, Textstatus, Errorthrown) {$ (' #msg '). TexT (xmlhttprequest.status + ' | | | ' + xmlhttprequest.readystate + ' | | | ' + textstatus);
    }
      });
  }); }) </script>

After the completion of the front desk encryption needs to do decryption processing, decryption completed after the need to use MD5 encryption existing password and database user password to compare authentication, if the verification through the need to write cookies to the next time users can log in from   , Because I do not want the user name and password in the cookie is stored in plaintext, I use the AES encryption method, a custom 32-bit encryption key to encrypt and decrypt the cookie processing, background C # code such as  :  

[HttpPost] public jsonresult userlogin (string UserName, String Pwd, String Key, String rurl) {string Priva
      Tekey = Common.cacheget (Key) as String; if (!string. IsNullOrEmpty (Privatekey)) {if (string). IsNullOrEmpty (UserName)) {return Json (new {result = FALSE, message = "User name is Empty"}, jsonrequestbehavior.al
        Lowget); } if (string. IsNullOrEmpty (PWD)) {return Json (new {result = FALSE, message = "User password is blank"}, JSONREQUESTBEHAVIOR.ALLOWG
        ET); string pwd = Common.decryptrsa (pwd, privatekey);//private key decrypts string md5pwd = Common.noneencrypt (common.noneenc Rypt (Common.noneencrypt (PWD, 1), 1), 1)//encrypts the decrypted value MD5 3 times accountunserinfo userInfo = BLL.
        GetUserInfo (Username.trim (), md5pwd); if (userInfo!= null && userinfo.u_id > 0)//user information exists {//username, password put cookie HttpCookie Co
          Okie = new HttpCookie ("Fw_izz"); AES Encrypted Cookie cookie["u_name"] = Aesencrypthelper.encryptaes (UserName);
          cookie["u_pwd"] = Aesencrypthelper.encryptaes (PWD); Cookie.
          Expires = DateTime.Now.AddDays (7);
          RESPONSE.COOKIES.ADD (cookie); if (!string.
          IsNullOrEmpty (Rurl))//Receive the value in the hidden field {return Json (new {result = true, message = success, url = rurl}); else {return Json (new {result = true), message = "Success", url = "/accountdetail/in
          Dex "});  } else {return Json (new {result = False), message = "User information does not exist", url = "/account/index"
        });
      } else {return Json (new {result = FALSE, message = "Illegal secret key", url = "/account/index"}); }
    }

Various encryption decryption methods, cache operation and cookie operation code are as follows:  

The public class Common {///<summary>///produces a set of RSA keys, private keys///</summary>///<returns>< /returns> public static dictionary<string, string> Creatersakeypair () {var keyPair = new Dictionar
      Y<string, string> ();
      var rsaprovider = new RSACryptoServiceProvider (1024);
      RSAParameters parameter = Rsaprovider.exportparameters (true); Keypair.add ("Public", bytestohexstring (parameter). Exponent) + "," + bytestohexstring (parameter.
      modulus));
      Keypair.add ("PRIVATE", Rsaprovider.toxmlstring (true));
    return keyPair; ///<summary>///RSA decryption string///</summary>///<param name= "EncryptData" > Ciphertext </param&
    Gt <param name= "Privatekey" > Private key </param>///<returns> plaintext </returns> public static string Dec
      Ryptrsa (String encryptdata, String privatekey) {string decryptdata = ""; try {var provider = new RsacryptoserviceprovidER (); Provider.

        Fromxmlstring (Privatekey); byte[] result = provider.
        Decrypt (Hexstringtobytes (EncryptData), false);
        ASCIIEncoding enc = new ASCIIEncoding (); Decryptdata = Enc.
      GetString (result);
      catch (Exception e) {throw new Exception ("RSA decryption Error!", e);
    return decryptdata;

      private static string bytestohexstring (byte[] input) {StringBuilder hexstring = new StringBuilder (64); for (int i = 0; i < input. Length;
      i++) {hexstring.append (String.Format ("{0:x2}", Input[i));
    return hexstring.tostring (); public static byte[] Hexstringtobytes (string hex) {if (hex).
      Length = = 0) {return new byte[] {0}; } if (hex.
      Length% 2 = 1) {hex = "0" + hex; } byte[] result = new Byte[hex.
      LENGTH/2]; for (int i = 0; i < hex. LENGTH/2; i++) {Result[i] = byte. Parse (Hex. Substring (2 * I, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
    return result;
    private static ObjectCache Cache {get {return memorycache.default} ///<summary>///Get cache///</summary>///<param name= "key" ></param>///
    ;returns></returns> public static Object Cacheget (string key) {return cache[key]; ///<summary>///Settings Cache///</summary>///<param name= "key" ></param>/// ;p Aram name= "Data" ></param>///<param name= "cacheTime" ></param> public static void CacheSet (
      String key, object data, int cacheTime) {cacheitempolicy policy = new CacheItemPolicy (); Policy.
      absoluteexpiration = DateTime.Now + timespan.fromminutes (cacheTime);
    Cache.Add (New CacheItem (key, data), policy); ///<summary>///To determine if cache exists///</summary>///<param name= "key" ></param>///<returns></returns> public static bool IsSet (string key) {return (cache[
    Key]!= null); ///<summary>///Cache invalidation///</summary>///<param name= "key" ></param> public
    static void CacheRemove (String key) {Cache.remove (key); ///<summary>///Encrypt strings (irreversible)///</summary>///<param name= "Password" > Strings to be encrypted </ 
    param>///<param name= "Format" > Encryption mode, 0 is sha1,1 is md5</param>///<returns></returns>
      public static string Noneencrypt (string Password, int Format) {string strresult = ""; Switch (Format) {Case 0:strresult = FormsAuthentication.HashPasswordForStoringInConfigFile (PASSW
          Ord, "SHA1");
        Break
          Case 1:strresult = FormsAuthentication.HashPasswordForStoringInConfigFile (Password, "MD5");
        Break Default:strresUlt = Password;
      Break
    return strresult;
 }
  }

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.