JSP Mail retrieve password all Raiders

Source: Internet
Author: User
Tags md5 encryption email account



@ Author Joy-zhuang

General large-scale Web site when we log in, the password forgot to have a function to retrieve the password.
To count the approximate method:
1. Send the password directly to your email address. It is usually a temporary password. 2. SMS verification, high cost. 3. Security issues 4. Send a link to your email and click to change your password.
I think the fourth method is the most cost-effective, this time is mainly engaged in this.


Make a night, the mail only send the function to write a fast 300 lines, although many are comments and spaces, was the roommate said, with Python only wrote 20 lines, can not help but worship Python! But anyway, the package is good, the next time it is convenient to use. Most of the code is for reference on the web and some of their own writing.

First of all, the idea:
Reference: http://blog.yidongzhifu.net/2014/03/07/mailbox Retrieve password function implementation/ when users fill out their own mailbox, they need to see if the mailbox is tied to the user ID and the message will be sent only if it matches. The most important thing in this email is a link address: url = baseUrl + "? uid=" + UID + "&validkey=" + Validkey; This address contains two parameters, ID user's Id,validkey authentication code, which is a string encrypted by MD5. The MD5 is used to ensure that the file is not modified during transmission, the encrypted string should contain the user's id+ expiration time + random number validkey=md5 (uid + "|" + outdate + "|" + Secretkey);


To put it bluntly, you need to get your password back, you have to enter your account number and email address first. Then the system to judge, the account number and the mailbox is matching. Then at this moment in another table to write down the information (Usrid,outdate,url) that is your ID, the expiration time (with the current time plus x minutes of validity), the URL is sent by the link.
Sent link = baseUrl + "? uid=" + UID + "&validkey=" + Validkey;
For example, my local address is localhost:8080/homeseller/resetpassword.jsp This is the address of the page where I reset my password. And then I'll add it to the address bar. ' Then fill in the incoming attribute and the corresponding value in the back to pass the value. For example, one of my Links: localhost:8080/homeseller/resetpassword.jsp? uid=zhuang123&validkey=36b0f 10812 de6d2b0d3b2dc044f9a27d It means passing in the ID, and Vaildkey Vaildkey We've written to the database before!

after successful completion, use JavaMail to send mail to the designated mailbox. Then you click on the link and pass the value. This time in the JSP to determine the corresponding UserID Validkey is not the same as in the database, and currenttime is not larger than the outdate is not expired. If you are satisfied, jump to the page where you changed your password. Changing the password is simply SQL, which is not spoken here.

OK, let's say the following code:
First,
(1) database layer (DAO ):It says the code to insert the information into the database (code is very simple to add and delete changes
Retrieve the password, insert the information, here the date is java.sql.Datepublic int insertinfor (Connection con,string userid,string email,timestamp Date, String signature) throws Sqlexception{string sql = "INSERT into Findpass (userid,email,outdate,signature) VALUES (?,?,?,?)" ; PreparedStatement pstmt = con.preparestatement (sql);p stmt.setstring (1, userId);p stmt.setstring (2, email); Pstmt.settimestamp (3,date);p stmt.setstring (4, signature); int res = Pstmt.executeupdate ();p stmt.close (); Con.close () ; return res;} Retrieve password, query whether the password can be modified public boolean ischangepass (String userid,string validkey) throws Exception{dbutil Dbutil = new Dbutil ( ); Connection con = Dbutil.getcon (); String sql = "SELECT * from findpass where userId =?"; PreparedStatement pstmt = con.preparestatement (sql);p stmt.setstring (1, userId); ResultSet res = Pstmt.executequery (), if (Res.last ()) {String signature = res.getstring ("signature"); Validkey.equals (signature)) {pstmt.close (); Con.close (); return false;} Else{long current = System.currenttimemillis (); Long time = Res.gettimestaMP ("Outdate"). GetTime (); if (current> time) {pstmt.close (); Con.close (); return false;} Else{pstmt.close (); Con.close (); return true;}}} Else{pstmt.close (); Con.close (); return false;}}






(2) Servlet code is based on the thinking of the corresponding processing
public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {// The split process is string method = Request.getparameter ("method"), if (Method.equals ("find")) {string userId = Request.getparameter (" UserId "); String useremail = Request.getparameter ("UserEmail"); Connection con = null;try {con = Dbutil.getcon ()} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrac E ();} Boolean flag = false;try {flag = Userdao.judgeusereamil (userId, useremail);} catch (Exception E1) {//TODO auto-generated Catch Blocke1.printstacktrace ();} if (flag) {Long currenttime = System.currenttimemillis () + 120000;date time = new Date (currenttime); Timestamp ts = new Timestamp (Time.gettime ()); Random random = new random (); String key = UserId + "|" + ts + "|" + random.nextint (); String signature = MD5UTIL.MD5 (key); try {int res = userdao.insertinfor (Con, userId, useremail, TS, signature); if (res==1) { SendMail SendMail = new SendMail (); String url = "localhost:8080/homeseller/rEsetpassword.jsp "+"? uid= "+ userId +" &validkey= "+ signature;sendmail.send (useremail, URL);}} catch (SQLException e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (Addressexception e) {//Todo auto-g Enerated catch Blocke.printstacktrace ();} catch (Messagingexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} Else{request.setattribute ("Error", "username and mailbox does not match, please re-enter!") ");}} Reset Password Else if (method.equals ("reset")) {String UserID = request.getparameter ("userid"); String Password = request.getparameter ("Password1"); try {Connection con = Dbutil.getcon (); Userdao.updatepassword (Con, Userid,password); Request.setattribute ("Error", "modified successfully, please login again!") "); Request.getrequestdispatcher (" login.jsp "). Forward (request, response);} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}







(3) Tool class
Tool Class A total of two categories MD5 Encryption, the implementation of the above-mentioned Validkey encryption processing to prevent manual identification.
Package Com.homeseller.util;import Java.security.messagedigest;import Java.security.messagedigest;public class Md5util {public final static string MD5 (string s) {char hexdigits[]={' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' D ', ' E ', ' F '};try {byte[] btinput = S.getbytes ();//MD5 object for MessageDigest digest algorithm messagedigest mdinst = Messagedigest.getinstance ("MD5");//Use the specified byte to update the digest mdinst.update (btinput);//Get ciphertext byte[] MD = Mdinst.digest ();// Convert ciphertext to 16 binary string form int j = Md.length;char str[] = new Char[j * 2];int k = 0;for (int i = 0; i < J; i++) {byte byte0 = md[i ];str[k++] = hexdigits[byte0 >>> 4 & 0xf];str[k++] = hexdigits[byte0 & 0xf];} return new String (str); catch (Exception e) {e.printstacktrace (); return null;}} public static void Main (string[] args) {System.out.println (Md5util.md5 ("20121221")); System.out.println (MD5UTIL.MD5 ("Encryption"));}}






The second category is the Mail sending class
Reference http://www.cnblogs.com/codeplus/archive/2011/10/30/2229391.html Java Mail is the use of existing mail accounts to send mail tools, for example, I registered an email account in NetEase, through the control of Java mail, I can not personally login NetEase mailbox, let the program automatically use NetEase mailbox to send mail. This mechanism is widely used in such aspects as registration activation and the sending of spam messages. JavaMail can go to http://www.oracle.com/technetwork/java/javamail/index-138643.html download and add Mail.jar to classpath.

The general process for sending Java mail is this:

1. Build a concrete class that inherits from Javax.mail.Authenticator, and rewrite the Getpasswordauthentication () method inside. This class is used as a login check to ensure that you have the right to send mail to the mailbox.

2. Build a properties file that contains parameters such as the SMTP server address.

3. Create a javax.mail.Session by building the properties file and Javax.mail.Authenticator concrete class. The session is created in the same way as a login mailbox. The rest of the nature is new mail.

4, the construction of mail content, is generally javax.mail.internet.MimeMessage object, and designated sender, recipient, subject, content and so on.


5. Use the Javax.mail.Transport tool class to send mail.



Here I refer to the written message class is only support SMTP and not support the other two, so there is no time to write the factory class. But SMTP should be enough. Today TX has a bug send not go out to change a mailbox is OK.
1, the first is a specific class inherited from Javax.mail.Authenticator. The Getpasswordauthentication () method is to build a Passwordauthentication object and return it, a bit confusing with the design intent of Java Mail, It may be that Javax.mail.Authenticator provides us with additional security-proof verification measures.
Package Com.homeseller.util;import Javax.mail.authenticator;import Javax.mail.passwordauthentication;public class Mailauthenticator extends Authenticator{private string username;private string Password;public mailauthenticator ( String username,string password) {this.username = Username;this.password = password;} String GetPassword () {return password;} @Overrideprotected passwordauthentication getpasswordauthentication () {return new passwordauthentication (username, password);} String GetUserName () {return username;} public void SetPassword (String password) {this.password = password;} public void Setusername (String username) {this.username = username;}}




2, the Mail sending class, the rest of the steps are implemented in this class. The Simplemail in the code is a pojo that encapsulates the subject and content of the message. This method is overloaded by the feeling that it is not appropriate to include both the subject and the content in a method parameter. Also, because most mailbox SMTP server addresses can be calculated by email address, for simplicity, a constructor that does not require an SMTP server address is provided.

Package Com.homeseller.util;import Java.util.list;import Java.util.properties;import javax.mail.MessagingException ; Import Javax.mail.session;import Javax.mail.transport;import Javax.mail.internet.addressexception;import Javax.mail.internet.internetaddress;import Javax.mail.internet.mimemessage;import Javax.mail.internet.mimemessage.recipienttype;public class Simplemailsender {/** Simple Mail sender, single, bulk *//**** send mail props file */private final transient Properties props = system.getproperties ();/** mail server login verification */private transient Mailauthenticator authenticator;/*** mailbox session*/private transient Session session;/*** Initialize Mail sender * * @param smtphostname* SMTP mail server address * @ param username* The user name (address) to send the message * @param password* the password to send the message */public simplemailsender (final string smtphostname,final string username,final String password) {init (username,password,smtphostname);} /*** Initialize the Mail sender * * @param username* the user name (address) of the message sent, and resolve the SMTP server address * @param password* the password for sending the message **/public Simplemailsender (final String Username,final string password) {//Resolves the SMTP server through the mailbox address, which works for most mailboxes final String smtphostname = "smtp." +username.split ("@") [1];init (Username,password,smtphostname);} /*** Initialize * * @param username* user name (address) * @param password* Password * @param smtphostname* SMTP host address */private void init (String use Rname,string password,string smtphostname) {//Initialize Propsprops.put ("Mail.smtp.auth", "true");p Rops.put (" Mail.smtp.host ", smtphostname);//Verify authenticator = new Mailauthenticator (Username,password);//Create sessionsession = Session.getinstance (props,authenticator);} /*** Send mail * * @param recipient* Recipient Email * @param subject* Message subject * @param content* message content * * @throws addressexception* @throws Mess agingexception*/public void Send (String recipient,string subject,object content) throws Addressexception, messagingexception{//Create MIME type message final mimemessage message = new MimeMessage (session);//Set Sender Message.setfrom (new InternetAddress (Authenticator.getusername ()));//Set the recipient Message.setrecipient (Recipienttype.to,new InternetAddress ( recipient));//Set Theme Message.setsubject (subject);//Set up mailContent Message.setcontent (content.tostring (), "text/html;charset=utf-8");//Send transport.send (message);} /**** Bulk Mail * * @param recipients* Recipients * @param subject* subject * @param content* content * throws addressexception* throws Messagingexc eption*/public void Send (list<string> recipients,string subject, Object content) throws Addressexception, messagingexception{//Create MIME type message final mimemessage message = new MimeMessage (session);//Set Sender Message.setfrom (new InternetAddress (Authenticator.getusername ()));//Set the recipient final int num = Recipients.size (); internetaddress[] Addresses = new Internetaddress[num];for (int i=0;i<num;i++) {Addresses[i] = new InternetAddress (Recipients.get (i));} Message.setrecipients (recipienttype.to,addresses);//Set Theme Message.setsubject (subject);//Set message content Message.setcontent (Content.tostring (), "text/html;charset=utf-8");//Send transport.send (message);} /*** Send mail * * @param recipient* recipient's email address * @param mail* Mail Object * @throws addressexception* @throws messagingexception*/public voi D Send (String Recipient,simPlemail Mail) throws Addressexception,messagingexception{send (Recipient,mail.getsubject (), mail.getcontent ());} /*** Bulk Mail * * @param recipients* Recipients * @param * Mail Object * @throws addressexception* @throws messagingexception**/public void send (list<string> Recipients,simplemail Mail) throws Addressexception,messagingexception{send (recipients, Mail.getsubject (), mail.getcontent ());}} 3.pojo:simplemailpackage com.homeseller.util;/* * Simplemail * PROJ */public class Simplemail {private String Content;pri Vate string Subject;public string getcontent () {return Content;} public void SetContent (String Content) {this. content = content;} Public String Getsubject () {return Subject;} public void Setsubject (String Subject) {this. Subject = Subject;}}






4. The final class to send
Package Com.homeseller.util;import Java.util.list;import Java.util.arraylist;import javax.mail.MessagingException; Import Javax.mail.internet.addressexception;public class SendMail {public void send (String email,string URL) throws Addressexception, Messagingexception{simplemailsender SMS = new Simplemailsender ("[Email protected]", "password"); String recipients = email;sms.send (recipients, "Homeseller Retrieve password", "Dear Homeseller User, in order to retrieve your password, please click on the following connection within two minutes:" +url+ " If you do not do this, ignore this message. ");} public static void Main (string[] args) throws Addressexception, messagingexception{simplemailsender SMS = new Simplemails Ender ("[Email protected]", "383160100033"); arraylist<string> recipients = new arraylist<string> () recipients.add ("[email protected]"); for (String recipient:recipients) {sms.send (recipients, "Test tests", "Hello Hrwhisper.");}}







——————————————————————————————————————


Here basic OK all things connected together, it is very good to achieve the password back.
Previously did not understand the principle, see the mail sent to do not know what things, now understand the natural happy, learning should be based on this continuous learning process of constant satisfaction!

JSP Mail retrieve password all Raiders

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.