Java Implementation mailbox Retrieve password

Source: Internet
Author: User
Tags ord url example

"Source Network: Http://www.cnblogs.com/zyw-205520/p/3738439.html"

The realization of the function of retrieving password by mail

1, recently developed a system, there is a need to forget the password after the mailbox back. Now the system at the time of registration will be forced to enter the mailbox, its purpose is to get back through the mail binding, can be password back. The ability to send mail through Java I will not say, focus on retrieving the password.

2, refer to other people's ideas: Send mail → url→ verification in the request email url→{authentication successfully changed password, unsuccessful jump to failure page}

The point is how to generate this URL and how to parse it.
Note that a URL can only be modified once password, when the same account sends multiple messages, only the last message of the URL mailbox

3, encryption can prevent forgery attacks, one URL can only be verified once, and bind the user. Generate URL: The random key can be generated with the UUID.

Digital signature = MD5 (user name + '′+A +"

' + Key key ')
Database fields (user name (primary key), key key, expiration time)
URL parameters (user name, digital signature), the generation of key key: Generate a key key for this user when each user retrieves the password

URL example:http://www.wechat68.com:80/cardsshok/checklink?sid=k3xhoi4o/uihh5qywbdfya==&username=123

Generates an expiration time, generates a digital signature, generates a URL, and sends a message. Addu (username, key, expiry time)

The database to use is as follows

PackageCom.soq.card.web.action;ImportJava.sql.Timestamp;ImportJava.util.List;ImportJava.util.UUID;ImportOrg.hibernate.Criteria;ImportOrg.hibernate.Session;ImportOrg.hibernate.SessionFactory;ImportOrg.hibernate.criterion.Restrictions;ImportOrg.springframework.orm.hibernate3.HibernateTemplate;ImportCom.soq.card.biz.UserHander;ImportCom.soq.card.entity.Users;ImportCom.soq.card.tools.DBhepler;ImportCom.soq.card.tools.Mail;ImportCOM.SOQ.CARD.TOOLS.MD5;ImportCom.soq.card.web.base.BaseAction;/***@authorJaven * @Email [Email protected] **/PublicClass PassemailactionExtendsbaseaction {PrivateUsers users;PrivateUserhander Userhander;PrivateString email;PrivateString SID;PrivateString UserName;PublicString SendMail () {Try{Hibernatetemplate HT =This. Getuserhander (). Getusersdao (). Gethibernatetemplate (); Sessionfactory factory =Ht.getsessionfactory (); Session session =Factory.opensession (); Criteria = Session.createcriteria (Users.Class); Criteria.add (Restrictions.eq ("LoginName", email)); list<users> list =Criteria.list ();if (list.size () > 0) {users=list.get (0); Mail mail =NewMail (); String Secretkey = Uuid.randomuuid (). toString ();//Key Timestamp outdate =New Timestamp (System.currenttimemillis () + 30 * 60 * 1000);//Expires after 30 minutesLong date = Outdate.gettime ()/1000 * 1000;//Ignore the number of milliseconds mySql fetch time is ignoring the number of millisecondsDbhepler bhepler=NewDbhepler (); String sql= "Update users set outdate=?,validatacode=?" where loginname=?; "; String str[] ={outdate+ "", Secretkey,users.getloginname ()}; Bhepler. Addu (SQL, str);//This.getuserhander (). Getusersdao (). Gethibernatetemplate (). Update (users);//Save to Database System.out.println ("username>>>>" +Users.getusername ()); String key =users.getusername () + "$" + Date + "$" +Secretkey; System.out.println ("key>>>" +Key); String digitalsignature = MD5.MD5 (key);//Digital signaturesString Path =This. Getrequest (). Getcontextpath (); String BasePath =This.getrequest (). Getscheme () + "://" +This.getrequest (). getServerName () + ":" +This.getrequest (). Getserverport () + path + "/"; String resetpasshref = basepath + "checklink?sid=" + digitalsignature + "&username=" +Users.getusername (); String emailcontent = "Do not reply to this message. Click on the link below to reset the password <br/><a href=" + resetpasshref + "target= ' _blank ' >" +Resetpasshref + "</a> or <a href=" +Resetpasshref + "target= ' _blank ' > Click I reset Password </a>" + "<br/>tips: This message is more than 30 minutes, the link will expire, need to re-apply ' recover password ' +Key + "\ T" +DigitalSignature; Mail.setto (email); Mail.setfrom ("XX");//Your e-mail mail.sethost ("smtp.163.com"); Mail.setusername ("[email protected]");//User Mail.setpassword ("CXXX");//Password Mail.setsubject ("[QR Code card] Retrieve your account password"); Mail.setcontent (emailcontent);If(Mail.sendmail ()) {System.out.println ("Send succeeded");This.getrequest (). SetAttribute ("MESG", "Reset password email has been sent, please login to reset the mailbox!" ");Return "SendMail"; } }Else{This.getrequest (). SetAttribute ("MESG", "User name does not exist, you will not forget the mailbox?");Return "Nouser"; } }Catch(Exception e) {//Todo:handle exceptionE.printstacktrace (); }ReturnNull; }PublicString Checkresetlink () {System.out.println ("sid>>>" +SID);if (Sid.equals ("") | | Username.equals ("")) {This.getrequest (). SetAttribute ("MESG", "link incomplete, regenerate"); SYSTEM.OUT.PRINTLN (">>>>> null");Return "Error"; } hibernatetemplate HT =This. Getuserhander (). Getusersdao (). Gethibernatetemplate (); Sessionfactory factory =Ht.getsessionfactory (); Session session =Factory.opensession (); Criteria = Session.createcriteria (Users.Class); Criteria.add (Restrictions.eq ("UserName", UserName)); list<users> list =Criteria.list ();if (List.size () >0) {users=list.get (0); Timestamp outdate =(Timestamp) users.getoutdate (); System.out.println ("outdate>>>" +Outdate);if (Outdate.gettime () <= System.currenttimemillis ()) {//Indicates that it has expiredThis.getrequest (). SetAttribute ("MESG", "the link has expired, please re-apply to retrieve the password.")); System.out.println ("Time timed out");Return "Error"; } String key = Users.getusername () + "$" +outdate.gettime ()/1000*1000+ "$" +users.getvalidatacode ();//Digital signaturesSYSTEM.OUT.PRINTLN ("key link") +Key); String digitalsignature = MD5.MD5 (key);//Digital signaturesSystem.out.println ("digitalsignature>>>>" +DigitalSignature);if (!Digitalsignature.equals (SID)) {This.getrequest (). SetAttribute ("MESG", "link not correct, has expired?" re-apply.)); System.out.println ("not marked correctly");Return "Error"; }Else{//Link validation by going to the Modify Password pageThis.getrequest (). SetAttribute ("User", users);Return "Success"; } }Else{This.getrequest (). SetAttribute ("MESG", "link error, unable to find a matching user, please re-apply to retrieve the password.")return "error" public Users getusers () { Return users; public void Setusers ( The users users) {this.users = users,} public Userhander Getuserhander () {return userhander,} public void Setuserhander (Us Erhander userhander) {this.userhander = Userhander;} public String Getemail () {return email,} public void Setemail (STR ing email {this.email = email;} Public String GetSID () {return SID;} public void Setsid (String sid) {this.sid = SID; Public String GetUserName () {return userName;} public void Setusername (String userName) {this.username = UserName;} } 

Supplemental 1:timestamp Type objects are lost in milliseconds when they are saved to the data. For example: 2014-05-20 10:30:10.234 into the MySQL database when the 2013-05-20 10:30:10.0. Time becomes different, and Sid matches are not equal. So I did the operation of ignoring the precision.

Supplement 2: Fix Linux under title Chinese garbled

      Sun.misc.BASE64Encoder enc = new Sun.misc.BASE64Encoder ();      Mailmessage.setsubject (Mimeutility.encodetext (Mailinfo.getsubject (), "UTF-8", "B"));      Troubleshoot Linux message title garbled


Add 3: Why not directly insert SID into the users table? The direct comparison of SIDS is OK when validating.

SOURCE Link: http://pan.baidu.com/s/1sj1LBf3 Password: fa4x

Link: http://pan.baidu.com/s/1c07aGH6 Password: PAHK database

Java Implementation mailbox Retrieve password

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.