Java Implementation mailbox Retrieve password instance code _java

Source: Internet
Author: User
Tags md5 uuid

Realization of the function of retrieving password by mail
1, a recent development of a system, there is a need to forget the password after the mailbox back. Now the system in the registration will be forced to enter the mailbox, and its purpose is to be retrieved through the mail binding, you can retrieve the password. The function of sending mail through Java I will not say, focus on the return password.

2, refer to other people's thinking: Send mail → request url→ Verify url→{Verify successfully modify password, unsuccessful jump to failure page}

The point is how to generate this URL and how to parse the URL.
Note that a URL can only be modified once the password, when the same account to send more than one message, only the last email URL mailbox

3, encryption can prevent forgery attacks, a URL can only authenticate once, and bind the user. Generate URL: An accompanying secret key can be generated with a UUID.

Digital signature = MD5 (username + ' ′+ expiration + ' ′+ expiration + ' + key)

Database fields (user name (primary key), keys key, expiration time)

URL parameters (user name, digital signature), the creation of key keys: Each user to retrieve the password time for the user to generate a key keys,

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

The database used is as follows:

Retrieve the password code for the mailbox as follows:

Package com.soq.card.web.action;
Import Java.sql.Timestamp;
Import java.util.List;

Import Java.util.UUID;
Import Org.hibernate.Criteria;
Import org.hibernate.Session;
Import Org.hibernate.SessionFactory;
Import org.hibernate.criterion.Restrictions;

Import Org.springframework.orm.hibernate3.HibernateTemplate;
Import Com.soq.card.biz.UserHander;
Import Com.soq.card.entity.Users;
Import Com.soq.card.tools.DBhepler;
Import Com.soq.card.tools.Mail;
Import Com.soq.card.tools.Md5;

Import com.soq.card.web.base.BaseAction; /** * @author Javen * @Email zyw205@gmail.com * */public class Passemailaction extends Baseaction {private Users
  Users

  Private Userhander Userhander;
  Private String Email;
  Private String SID;
  
  Private String UserName; Public String SendMail () {try {hibernatetemplate ht = This.getuserhander (). Getusersdao (). Gethibernatetemplate (
      );
      Sessionfactory factory = Ht.getsessionfactory ();
      Session session = Factory.opensession (); CRiteria 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 = new mail (); String Secretkey = Uuid.randomuuid (). toString (); Key Timestamp outdate = new Timestamp (System.currenttimemillis () + 30 * 60 * 1000);//30 minutes after expiration long date
        = Outdate.gettime ()/1000 * 1000;//ignores the number of milliseconds MYSQL fetch time is the Dbhepler bhepler=new Dbhepler () that ignores milliseconds; 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 Signature String 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 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 more than 30 minutes, link will be invalidated, you need to reapply ' retrieve password ' + key + ' t ' + digitalsignature;
        Mail.setto (email);
        Mail.setfrom ("XX");//Your Mailbox Mail.sethost ("smtp.163.com"); Mail.setusername ("XXX@163.com");//user Mail.setpassword ("cxxx");/Password Mail.setsubject ("[two-dimensional code card] Retrieve your account password");
        Mail.setcontent (emailcontent);
          if (Mail.sendmail ()) {System.out.println ("sent successfully"); This.getrequest (). setattribute ("MESG", "Reset password Mail has been sent, please login to the mailbox to reset!")
          ");
        return "SendMail";
        } else {this.getrequest (). setattribute ("MESG", "username does not exist, you will not forget the mailbox?");
      return "Nouser";
    } catch (Exception e) {//Todo:handle Exception e.printstacktrace ();
  return null;

    Public String Checkresetlink () {System.out.println ("sid>>>" + SID); if (Sid.equals ("") | |
      Username.equals ("")) {this.getrequest (). setattribute ("MESG", "link incomplete, rebuild");
      SYSTEM.OUT.PRINTLN (">>>>> null");
    return "error";
    Hibernatetemplate ht = This.getuserhander (). Getusersdao (). Gethibernatetemplate ();
    Sessionfactory factory = Ht.getsessionfactory ();
    Session session = Factory.opensession (); Criteria 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 expired This.getrequest (). setattribute ("MESG", "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 signature
       SYSTEM.OUT.PRINTLN ("Key Link" "" +key); String digitalsignature = MD5.MD5 (key);//Digital Signature System.out.println ("digitalsignature>>>>" +digita
       Lsignature);
           if (!digitalsignature.equals (SID)) {this.getrequest (). setattribute ("MESG", "link is incorrect, has expired?)
          System.out.println ("incorrectly marked"); Return "Error";
        }else {//link validation by Go to modify Password page this.getrequest (). setattribute ("User", users);
      Return "Success";
      }}else {this.getrequest (). setattribute ("MESG", "link error, unable to find a matching user, please reapply to retrieve password.");
      SYSTEM.OUT.PRINTLN ("User does not exist");
    return "error";
  } Public Users Getusers () {return users;
  public void Setusers (users users) {this.users = users;
  Public Userhander Getuserhander () {return userhander;
  public void Setuserhander (Userhander userhander) {this.userhander = Userhander;
  Public String Getemail () {return email;
  public void Setemail (String 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 millisecond precision 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 has changed, and Sid matches are not equal. So I did an operation that ignores precision.

Add 2: Solve Linux under title Chinese garbled

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

Add 3: How not to insert the SID directly into the users table. It's OK to compare SIDS directly when validating.

SOURCE Download Address: http://pan.baidu.com/s/1cl8hKq

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.

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.