1 18 19 package org.apache.struts.util; 20 21 import java.security.MessageDigest ; 22 import java.security.NoSuchAlgorithmException ; 23 24 import javax.servlet.http.HttpServletRequest ; 25 import javax.servlet.http.HttpSession ; 26 27 import org.apache.struts.Globals; 28 import org.apache.struts.taglib.html.Constants; 29 30 39 public class TokenProcessor { 40 41 44 private static TokenProcessor instance = new TokenProcessor(); 45 46 49 public static TokenProcessor getInstance() { 50 return instance; 51 } 52 53 57 protected TokenProcessor() { 58 super(); 59 } 60 61 64 private long previous; 65 66 81 public synchronized boolean isTokenValid(HttpServletRequest request) { 82 return this.isTokenValid(request, false); 83 } 84 85 100 public synchronized boolean isTokenValid( 101 HttpServletRequest request, 102 boolean reset) { 103 104 HttpSession session = request.getSession(false); 106 if (session == null) { 107 return false; 108 } 109 110 String saved = (String ) session.getAttribute(Globals.TRANSACTION_TOKEN_KEY); 113 if (saved == null) { 114 return false; 115 } 116 117 if (reset) { 118 this.resetToken(request); 119 } 120 121 String token = request.getParameter(Constants.TOKEN_KEY); 123 if (token == null) { 124 return false; 125 } 126 127 return saved.equals(token); 128 } 129 130 137 public synchronized void resetToken(HttpServletRequest request) { 138 139 HttpSession session = request.getSession(false); 140 if (session == null) { 141 return; 142 } 143 session.removeAttribute(Globals.TRANSACTION_TOKEN_KEY); 144 } 145 146 152 public synchronized void saveToken(HttpServletRequest request) { 153 154 HttpSession session = request.getSession(); 155 String token = generateToken(request); 156 if (token != null) { 157 session.setAttribute(Globals.TRANSACTION_TOKEN_KEY, token); 158 } 159 160 } 161 162 168 public synchronized String generateToken(HttpServletRequest request) { 169 170 HttpSession session = request.getSession(); 171 try { 172 byte id[] = session.getId().getBytes(); 173 long current = System.currentTimeMillis(); 174 if (current == previous) { 175 current++; 176 } 177 previous = current; 178 byte now[] = new Long (current).toString().getBytes(); 179 MessageDigest md = MessageDigest.getInstance("MD5"); 180 md.update(id); 181 md.update(now); 182 return toHex(md.digest()); 183 } catch (NoSuchAlgorithmException e) { 184 return null; 185 } 186 187 } 188 189 193 private String toHex(byte buffer[]) { 194 StringBuffer sb = new StringBuffer (buffer.length * 2); 195 for (int i = 0; i < buffer.length; i++) { 196 sb.append(Character.forDigit((buffer[i] & 0xf0) >> 4, 16)); 197 sb.append(Character.forDigit(buffer[i] & 0x0f, 16)); 198 } 199 return sb.toString(); 200 } 201 202 } 203 | Popular Tags |