How to use cookies in JavaScript to implement password-remembering and cookie-related functions, and how to use cookies to remember passwords

Source: Internet
Author: User

How to use cookies in JavaScript to implement password-remembering and cookie-related functions, and how to use cookies to remember passwords

Cookie is a small text file placed on the client (browser) by website designers. It not only saves passwords, but also saves recent browsing records through cookies to improve user experience.

Add the Remember password function on the login interface. The first thing I think of is to call the cookie in the java background to store the account password, which is roughly as follows:

HttpServletRequest request HttpServletResponse responseCookie username = new Cookie("username ","cookievalue");Cookie password = new Cookie("password ","cookievalue");response.addCookie(username );response.addCookie(password );

However, for the sake of security, the passwords we obtain in the background are mostly the ciphertext encrypted by MD5 in js. If we put the ciphertext in the cookie, it does not work in js;

Then, consider accessing the cookie in js. The Code is as follows:

// Set cookievar passKey = '4c05c54d952b11e691d76c0b843ea7f9 '; function setCookie (cname, cvalue, exdays) {var d = new Date (); d. setTime (d. getTime () + (exdays * 24x60*60*1000); var expires = "expires =" + d. toUTCString (); document. cookie = cname + "=" + encrypt (escape (cvalue), passKey) + ";" + expires;} // obtain cookiefunction getCookie (cname) {var name = cname + "="; var ca = document. cookie. split (';'); for (var I = 0; I <ca. length; I ++) {var c = ca [I]; while (c. charAt (0) = '') c = c. substring (1); if (c. indexOf (name )! =-1) {var cnameValue = unescape (c. substring (name. length, c. length); return decrypt (cnameValue, passKey) ;}} return ";}// clear cookie function clearCookie (cname) {setCookie (cname ,"", -1 );}

The setCookie (cname, cvalue, exdays) parameters are the names of the stored cookies, the cookie value, and the cookie validity period.

Because the cookie cannot contain special characters such as equal signs, spaces, and semicolons, I use the escape () function to encode the string when setting the cookie. When obtaining the cookie, I use the unescape () function to decode it. However, the escape () function does not encode ASCII letters and numbers. Therefore, the accounts and passwords stored in cookies are stored in plain text, which is not safe. Therefore, I found an encryption and decryption algorithm for strings on the Internet. This algorithm requires two parameters: a string to be encrypted and a custom encryption key passKey. Encrypt (value, passkey) is used to encrypt the cookie. decrypt (value, passKey) is used to decrypt the cookie. This algorithm is appended to the end of this article.

Call the cookie access method:

1. Define checkbox

<Input type = "checkbox" id = "rememberMe" checked = "checked"/> remember the password

2. Make sure that the account and password are entered correctly before calling

if($('#rememberMe').is(':checked')){setCookie('customername', $('#username').val().trim(), 7)setCookie('customerpass', $('#password').val().trim(), 7)}

3. Go to the logon page and check whether there is an account and password in the cookie.

$ (Function () {// obtain cookievar cusername = getCookie ('mermername'); var cpassword = getCookie ('mermerpass'); if (cusername! = "" & Cpassword! = "") {$ ("# Username"). val (cusername); $ ("# password"). val (cpassword );}}

The string encryption and decryption algorithm is attached.

eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('A G(a,b){x(b==v||b.7<=0){D.y("z R P O");t v}6 c="";s(6 i=0;i<b.7;i++){c+=b.u(i).n()}6 d=m.r(c.7/5);6 e=l(c.9(d)+c.9(d*2)+c.9(d*3)+c.9(d*4)+c.9(d*5));6 f=m.M(b.7/2);6 g=m.B(2,C)-1;x(e<2){D.y("L K J z");t v}6 h=m.F(m.H()*N)%I;c+=h;w(c.7>q){c=(l(c.o(0,q))+l(c.o(q,c.7))).n()}c=(e*c+f)%g;6 j="";6 k="";s(6 i=0;i<a.7;i++){j=l(a.u(i)^m.r((c/g)*E));x(j<p){k+="0"+j.n(p)}Q k+=j.n(p);c=(e*c+f)%g}h=h.n(p);w(h.7<8)h="0"+h;k+=h;t k}A S(a,b){6 c="";s(6 i=0;i<b.7;i++){c+=b.u(i).n()}6 d=m.r(c.7/5);6 e=l(c.9(d)+c.9(d*2)+c.9(d*3)+c.9(d*4)+c.9(d*5));6 f=m.F(b.7/2);6 g=m.B(2,C)-1;6 h=l(a.o(a.7-8,a.7),p);a=a.o(0,a.7-8);c+=h;w(c.7>q){c=(l(c.o(0,q))+l(c.o(q,c.7))).n()}c=(e*c+f)%g;6 j="";6 k="";s(6 i=0;i<a.7;i+=2){j=l(l(a.o(i,i+2),p)^m.r((c/g)*E));k+=T.U(j);c=(e*c+f)%g}t k}',57,57,'||||||var|length||charAt||||||||||||parseInt|Math|toString|substring|16|10|floor|for|return|charCodeAt|null|while|if|log|key|function|pow|31|console|255|round|encrypt|random|100000000|the|change|plesae|ceil|1000000000|empty|be|else|cannot|decrypt|String|fromCharCode'.split('|'),0,{}))

PS: Next, let's take a look at js functions related to cookie operations.

// Set the cookie function. There are three parameters: cookie name, value, and cookie retention time. Unit: Day function SetCookie (name, value, days) {var days = arguments [2]? Arguments [2]: 30; // This cookie will be saved for 30 days var exp = new Date (); // new Date ("December 31,999 8"); exp. setTime (exp. getTime () + days * 86400000); document. cookie = name + "=" + escape (value) + "; expires =" + exp. toGMTString ();} // The cookie function getCookie (name) {var arr = document. cookie. match (new RegExp ("(^ |)" + name + "= ([^;] *) (; | $)"); if (arr! = Null) {return unescape (arr [2]);} return null;} // Delete the cookie function delCookie (name) {var exp = new Date (); exp. setTime (exp. getTime ()-1); var cval = getCookie (name); if (cval! = Null) {document. cookie = name + "=" + cval + "; expires =" + exp. toGMTString ();}}

The above section describes how to use cookies in JavaScript to implement password-remembering and cookie-related functions. I hope this will help you. If you have any questions, please leave a message, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.