ASP. net mvc combines JavaScript login, checksum encryption, mvcjavascript

Source: Internet
Author: User

ASP. net mvc combines JavaScript login, checksum encryption, mvcjavascript

Recently, I wrote my own household financial revenue and expenditure management system, which includes expenditure management, income management, and some statistical functions.

First, let's talk about the login module. Because GET and POST requests are involved, these items can be monitored and crawled. Therefore, we should consider using RSA encryption and decryption to transmit user name and password parameters. The JS page is as follows:

/* Three JS files, BigInt. js, RSA. js and Barrett. js. jquery needs to be introduced when cookie is used. cookie. js file * // interact with the background to obtain the public key function getPublicKey () {var pubKey = ''; if ($. cookie ('publickey') = null) {$. ajax ({url: "/Account/GetRsaPublicKey", type: "get", contentType: "application/x-www-form-urlencoded; charset = UTF-8", async: false, data: {}, dataType: "json", success: function (data) {if (data. 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;} // The Public Key encrypts the User Password Pwd as the 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 blank '); return;} if (pwd = '') {alert ('user password cannot be blank '); 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-urlencoded; charset = UTF-8", async: false, dataType: "json", success: function (data) {if (data. result = 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 front-end encryption is complete, the backend needs to perform decryption. After decryption is complete, the existing password needs to be encrypted using MD5 for comparison and verification with the user password in the database, if the verification is successful, you need to write a cookie so that the next user can log on automatically. Because I do not want the user name and password to be explicitly stored in the cookie, I use the AES encryption method here, customize a 32-bit encryption key to encrypt and decrypt the cookie. The c # code in the background is as follows:

[HttpPost] public JsonResult UserLogin (string UserName, string Pwd, string Key, string RUrl) {string privateKey = Common. CacheGet (Key) as string; if (! String. isNullOrEmpty (privateKey) {if (string. isNullOrEmpty (UserName) {return Json (new {result = false, message = "UserName is blank"}, JsonRequestBehavior. allowGet);} if (string. isNullOrEmpty (Pwd) {return Json (new {result = false, message = "User Password is blank"}, JsonRequestBehavior. allowGet);} string pwd = Common. decryptRSA (Pwd, privateKey); // Private Key decryption string md5Pwd = Common. noneEncrypt (Common. noneEncrypt (Common. N OneEncrypt (pwd, 1), 1); // encrypt the decrypted value md5 three times AccountUnserInfo userInfo = bll. getUserInfo (UserName. trim (), md5Pwd); if (userInfo! = Null & userInfo. u_Id> 0) // The user information exists {// the user name and password are put into the cookie HttpCookie cookie = new HttpCookie ("fw_izz "); // AES encryption 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) // receives the value {return Json (new {result = true, message = "success", url = RUrl}) from the hidden domain });} else {return Json (new {result = true, message = "success", url = "/AccountDetail/Index "});}} else {return Json (new {result = false, message = "user information does not exist", url = "/Account/Index "});}} else {return Json (new {result = false, message = "invalid key", url = "/Account/Index "});}}

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

Public class Common {// <summary> // generate a set of RSA public keys and private keys /// </summary> /// <returns> </returns> public static dictionary <string, string> CreateRsaKeyPair () {var keyPair = new Dictionary <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> /// <param name = "privateKey"> Private Key </param> // <returns> plaintext </returns> public static string DecryptRSA (string encryptData, string privateKey) {string decryptData = ""; try {var provider = new RSACryptoServiceProvider (); provi Der. 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 

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.