fs-danaus
2024-08-09 7204e3dff0490732e861ccd1338e3e3c31d768c6
提交 | 用户 | age
a6a76f 1 package com.yc.utils;
F 2
3 import java.security.MessageDigest;
4 import java.security.NoSuchAlgorithmException;
5
6 import javax.servlet.http.HttpServletRequest;
7 import javax.servlet.http.HttpSession;
8
9 /**
10  * 令牌生成类
11  * */
12 public class TokenUtil {
13
14     /**
15      * @param args
16      */
17     public static void main(String[] args) {
18         // TODO Auto-generated method stub
19         System.out.print(generateToken(null));
20
21     }
22
23 public static String generateToken(HttpServletRequest request) { 
24     HttpSession session = request.getSession(); 
25     try { 
26         byte id[] = session.getId().getBytes(); 
27         byte now[] = 
28             new Long(System.currentTimeMillis()).toString().getBytes(); 
29         MessageDigest md = MessageDigest.getInstance("MD5"); 
30         md.update(id); 
31         md.update(now); 
32         String token=bytesToHexString(md.digest());
33         session.setAttribute("_token",token );
34         return token; 
35     } catch (IllegalStateException e) { 
36         return (null); 
37     } catch (NoSuchAlgorithmException e) { 
38         return (null); 
39     } 
40
41 public static String bytesToHexString(byte[] src){
42        StringBuilder stringBuilder = new StringBuilder("");
43        if (src == null || src.length <= 0) {
44            return null;
45        }
46        for (int i = 0; i < src.length; i++) {
47            int v = src[i] & 0xFF;
48            String hv = Integer.toHexString(v);
49            if (hv.length() < 2) {
50                stringBuilder.append(0);
51
52            }
53            stringBuilder.append(hv);
54
55        }
56        return stringBuilder.toString();
57         }
58 }