A token implementation of the app token

Source: Internet
Author: User
Tags md5 digest

App login verification can not be used to determine the session. Then the data are said to use the token, did not find the right method, my vision is too small. In addition, it is more and more important to feel the foundation, for example, what the session is, I am speechless. Do not know what the session is, how to do the verification it. Then just about the load and destruction of classes, and so on. I need to look at the basics of Java again.

Here, I define a token class to store tokens. is a string + time stamp created. Then define a management class to maintain tokens. Simple implementation, but there are a lot of problems. For example, I understand the session (whether it can put the session, what state after the session), such as the definition of this class at the time of the call to load, at the end of the time, and I want to exist, this maintenance class how to ensure existence, this is the class of the declaration cycle problem, For example, loading into memory and caching implementations, the cache is used too little.

1.token.java

 1 package com.tixa.wedding.util; 2 3 Import java.io.Serializable;     4 5 public class Token implements Serializable {6 7/** 8 * @Fields Serialversionuid:todo 9 */10 Private static final Long Serialversionuid = -754659525548951914l;11 private String signature;12 Private Long Ti Mestamp;13 public Token (String signature, long timestamp) {if (signature = = null) thro W New IllegalArgumentException ("signature can not is null"); this.timestamp = timestamp;19th             Is.signature = signature;20}21 public Token (String signature) {(signature = null) 24     throw new IllegalArgumentException ("signature can not is null"); this.signature = signature;27 }28/**30 * Returns A string containing the unique signatureentifier assigned to this token.31 */3    2 public String Getsignature () {return signature;34}35 The public long Gettimestamp () {PNS return timestamp;38}39/**41 * Timestamp is not considered, because even TI     Mestamp different also considered to be the same token.42 */43 public int hashcode () {signature.hashcode (); 45}46 47 public Boolean equals (Object object) {(object instanceof token)-return (token) Object. Sign         Ature.equals (this.signature); false;51}52 @Override54 public String toString () {55 Return "Token [signature=" + Signature + ", timestamp=" + timestamp56 + "]"; 57}58 59 60}

2.tokenutil.java

  1 package com.tixa.wedding.util;  2 3 Import Java.security.MessageDigest;  4 Import Java.util.Calendar;  5 Import Java.util.Date;  6 Import Java.util.HashMap;  7 Import Java.util.Map;  8 Import Java.util.Map.Entry; 9 Import java.util.concurrent.Executors; Ten import Java.util.concurrent.ScheduledExecutorService; Import Java.util.concurrent.TimeUnit; Import Org.apache.log4j.Logger; All public class Tokenutil {INTERVAL = 7;//token expiration interval days of the private s Tatic final String YAN = "testmrf1$789787aadfjkds//*-+ ' []jfeu;384785*^*&%^%$%";//Add salt to the private static final int H our = 3;//check token expiration thread execution time is Logger Logger = Logger.getlogger ("visit"); private static Map<integer, token> Tokenmap = new Hashmap<integer, token> (); The private static tokenutil tokenutil = null;  Static Scheduledexecutorservice scheduler =executors.newsinglethreadscheduledexecutor ();   28 29  static {Logger.info ("\n=============== enters tokenutil static code block =================="); Listentask (); 32 }, public static Tokenutil Gettokenutil () {tokenutil = = null) {PNS Syninit () ; to Tokenutil; synchronized void Syninit () {if (Tokenutil = = null) {Tokenu til = new Tokenutil (); Tokenutil () {()}, the public static Map<integer, Ken> Gettokenmap () {return tokenmap; 56} 57 58/** 59 * Generate a token */the public s Tatic token Generatetoken (String uniq,int ID) {Token token = new token (MD5 (System.currenttimemillis () +yan+uniq +id), System.currenttimemillis ()); Synchronized (Tokenmap) {tokenmap.put (ID, token); /** * @Title: REmovetoken * @Description: Remove token @param @param nonce * @param @return parameters * @return Boo             Lean return type */-public static Boolean removetoken (int id) {synchronized (Tokenmap) {79 Tokenmap.remove (ID); Logger.info (tokenmap.get (id) = = null? "\n========= cancelled ========": "\n++++++++ logoff failed +++++++++++++++"); Bayi} The return true; /** * @Title: Volidatetoken * @Description: Check token * @param @param signature * * @param @param nonce * @param @return Parameter * @return Boolean return type * * * * public static B Oolean Volidatetoken (String signature, int id) {94 Boolean flag = False, and token token = (token) Tokenma P.get (ID); if (token! = null && token.getsignature (). Equals (signature)) {Logger.info ("\n===== is online = = ====="); 98 flag = true;   }100 101 Return flag;102  }103 104/**105 * 106 * @Title: MD5107 * @Description: Encrypted 108 * @param @param s109 * @pa Ram @return Parameter * @return string return type 111 */112 public final static String MD5 (string s) {113 try { byte[] Btinput = S.getbytes (); 115//MessageDigest object for MD5 Digest algorithm MessageDigest             Mdinst = Messagedigest.getinstance ("MD5"); 117//Use the specified byte to update the Digest 118 mdinst.update (btinput); 119 Get ciphertext return Byte2hex (Mdinst.digest ()); 121} catch (Exception e) {122 E.printsta Cktrace (); 123 return null;124}125}126 127/**128 * Convert byte array to 16 binary string 129 * @param B13 0 * @return131 */132 private static String Byte2hex (byte[] b) {133 StringBuilder sbdes = new STRINGB Uilder (); 134 String tmp = null;135 for (int i = 0; i < b.length; i++) {136 TMP = (integer.t Ohexstring (B[i] & 0xFF)), 137 if (tmp.length () = = 1) {138 Sbdes.append ("0"); 139}140 Sbdes.     Append (TMP); 141}142 return sbdes.tostring (); 143}144 145/**146 * @Title: Listentask 147 * @Description: Timed token Expiration Cleanup Task 148 * @param parameter 149 * @return void return type */151 public static V OID Listentask () {Calendar calendar = Calendar.getinstance (); 153 int year = Calendar.get (calendar.year)         ; 154 int month = Calendar.get (calendar.month); 155 int day = Calendar.get (calendar.day_of_month); 156 Customize the HOUR point of the day, starting tomorrow 157 Calendar.set (year, month, Day+1, HOUR, 0, 0); 158//Calendar.set (year, month, day, 159 Date date = Calendar.gettime (); 161 scheduler.scheduleatfixedrate (New Listento     Ken (), (Date.gettime ()-system.currenttimemillis ())/1000, 60*60*24, timeunit.seconds); 162}163 164 165 166 /**167 * @ClassName: ListenToken168 * @Description: Monitor token expiration thread runnable implementation 169 * @author mrf170 * @date 2015-10-21 PM 02:22:24171             * 172 */173 Static class Listentoken implements Runnable {174 public Listentoken () {175 Super (); 176}177 178 public void Run () {179 Logger.info ("\n************************** performs listening toke                     N List **************************** "), 181 synchronized (TOKENMAP) {182                             for (int i = 0; i < 5; i++) {183 if (tokenmap! = null &&!tokenmap.isempty ()) {184                                 For (Entry<integer, token> entry:tokenMap.entrySet ()) {185 Token token = (token) entry.getvalue (); 186 Logger.info ("\n============== Logged in User:" +entry + "====================="); 187//try {thread.sleep (n);} catch (Interruptedexception e) {E.P Rintstacktrace ();}   188                              int interval = (int) ((System.currenttimemillis ()-Token.gettimestamp ())/1000/60/60/ 189 if (interval > interval) {tokenmap.rem Ove (Entry.getkey ()); 191 logger.info ("\n============== Remove token:" + entry+ "=============                     ======== "); 192}193 194}195}196 }197 198}199} catch (Exception e) {$ l Ogger.error ("Token Listener thread Error:" +e.getmessage ()); 201 E.printstacktrace (); 202}203}204} 205 206 207 208 public static void main (string[] args) {209 System.out.println (Generatetoken ("s", 1))         ; System.out.println (Generatetoken ("Q", 1)), 211 System.out.println (Generatetoken ("S3", 2)); 212 System.out.println (GenerAtetoken ("S4", 3)); 213 System.out.println (Removetoken (3)); 214 System.out.println (Gettokenmap ()); 215}2   16 217}218 219

A token implementation of the app token

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.