LtpaToken.java 8.41 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
package pwc.taxtech.atms.web.controller;

import org.apache.commons.codec.binary.Base64;

import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;


public class LtpaToken {
    private byte[] header;
    private byte[] creation;
    private byte[] expires;
    private byte[] user;
    //SHA-1校验和(长度20)
    private byte[] digest;
    private Date creationDate;
    private Date expiresDate;
    private byte[] hash;
    private String ltpaToken;
    private Properties properties = null;
    private byte[] rawToken;

    /*
     * //Cookie name.
     * public final static String COOKIE_NAME =PropertiesUtil.findPropertyInClasspath("conf/sso-config.properties","sso.ltpa.cookie.name");///"LtpaToken";
     *
     * //private final static String COOKIE_DOMAIN = ".blabla.bla.NET";
     *
     * private final static String DOMINO_SECRET =PropertiesUtil.findPropertyInClasspath("conf/sso-config.properties","sso.ltpa.cookie.secret"); //"密钥";
     */
    public final static String COOKIE_NAME = "LtpaToken";
    //	private final static String DOMINO_SECRET = "JytUSYHnoFtU9dbkyXUny7FPn88="; // "密钥";
eddie.woo's avatar
eddie.woo committed
39
    private final static String DOMINO_SECRET = "1cgjI5oeU1VWrkJmdPFO+AwVRCE="; // "密钥" --- 生产环境key
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207

    public LtpaToken() {
        init();
    }

    public LtpaToken(String token) {
        init();
        ltpaToken = token;
        rawToken = Base64.decodeBase64(token);
        user = new byte[(rawToken.length) - 40];
        for (int i = 0; i < 4; i++) {
            header[i] = rawToken[i];
        }
        for (int i = 4; i < 12; i++) {
            creation[i - 4] = rawToken[i];
        }
        for (int i = 12; i < 20; i++) {
            expires[i - 12] = rawToken[i];
        }
        for (int i = 20; i < (rawToken.length - 20); i++) {
            user[i - 20] = rawToken[i];
        }
        for (int i = (rawToken.length - 20); i < rawToken.length; i++) {
            digest[i - (rawToken.length - 20)] = rawToken[i];
        }
        creationDate = new Date(Long.parseLong(new String(creation), 16) * 1000);
        setExpiresDate(new Date(Long.parseLong(new String(expires), 16) * 1000));
    }

    private void init() {
        creation = new byte[8];
        digest = new byte[20];
        expires = new byte[8];
        hash = new byte[20];
        header = new byte[4];
    }

    /**
     * 创建一个新的SHA-1代码>消息IGEST < /代码>实例
     *
     * @return
     * @method getDigest Create on 2018年6月29日 上午11:33:24
     * Copyright (c) 2018 by future-info.
     * @author caoj
     * @tel 15991758179
     * @mail caoj@landray.com.cn
     * @version 0.1
     */
    private MessageDigest getDigest() {
        try {
            return MessageDigest.getInstance("SHA-1");
        } catch (NoSuchAlgorithmException nsae) {
        }
        return null;
    }

    /**
     * 给定参数生成一个新的LTPATOKEN
     *
     * @param canonicalUser 登录名
     * @param tokenCreation token创建时间
     * @param tokenExpires  token过期时间
     * @return
     * @method generate Create on 2018年6月29日 上午11:32:26
     * Copyright (c) 2018 by future-info.
     * @author caoj
     * @tel 15991758179
     * @mail caoj@landray.com.cn
     * @version 0.1
     */
    public static LtpaToken generate(String canonicalUser, Date tokenCreation, Date tokenExpires) {
        LtpaToken ltpa = new LtpaToken();

        Calendar calendar = Calendar.getInstance();
        MessageDigest md = ltpa.getDigest();

        ltpa.header = new byte[]{0, 1, 2, 3};
        ltpa.user = canonicalUser.getBytes();

        byte[] token = null;
        calendar.setTime(tokenCreation);

        ltpa.creation = Long.toHexString(calendar.getTime().getTime() / 1000).toUpperCase().getBytes();
        calendar.setTime(tokenExpires);
        // calendar.add(Calendar.HOUR,8);

        ltpa.expires = Long.toHexString(calendar.getTime().getTime() / 1000).toUpperCase().getBytes();
        ltpa.user = canonicalUser.getBytes();

        token = concatenate(token, ltpa.header);
        token = concatenate(token, ltpa.creation);
        token = concatenate(token, ltpa.expires);
        token = concatenate(token, ltpa.user);
        md.update(token);
        ltpa.digest = md.digest(Base64.decodeBase64(DOMINO_SECRET));
        token = concatenate(token, ltpa.digest);

        return new LtpaToken(new String(Base64.encodeBase64(token)));
    }

    /**
     * 连接字节数组的帮助方法
     *
     * @param a
     * @param b
     * @return
     * @method concatenate Create on 2018年6月29日 上午11:33:47
     * Copyright (c) 2018 by future-info.
     * @author caoj
     * @tel 15991758179
     * @mail caoj@landray.com.cn
     * @version 0.1
     */
    private static byte[] concatenate(byte[] a, byte[] b) {
        if (a == null) {
            return b;
        } else {
            byte[] bytes = new byte[a.length + b.length];

            System.arraycopy(a, 0, bytes, 0, a.length);
            System.arraycopy(b, 0, bytes, a.length, b.length);
            return bytes;
        }
    }

    public String toString() {
        return ltpaToken;
    }

    /**
     * 通过获取cookie指定名称的token值,解析用户是否合法并
     * 返回用户名 或抛异常
     *
     * @param token
     * @return
     * @method validate Create on 2018年6月29日 上午11:34:24
     * Copyright (c) 2018 by future-info.
     * @author caoj
     * @tel 15991758179
     * @mail caoj@landray.com.cn
     * @version 0.1
     */
    public static String validate(String token) {
        LtpaToken ltpa = new LtpaToken(token);

        byte[] sh1 = null;
        MessageDigest md = ltpa.getDigest();
        sh1 = concatenate(sh1, ltpa.header);
        sh1 = concatenate(sh1, ltpa.creation);
        sh1 = concatenate(sh1, ltpa.expires);
        sh1 = concatenate(sh1, ltpa.user);
        md.update(sh1);
        //通过解析token值获取到的用户名
        System.err.println(new String(ltpa.user));
        byte[] ndigest = md.digest(Base64.decodeBase64(DOMINO_SECRET));
        //当前时间
        Long date = Calendar.getInstance().getTimeInMillis();
        //校验密文合法性、校验时间合法性
        if (Arrays.equals(ndigest, ltpa.digest) && date >= ltpa.creationDate.getTime() && date <= ltpa.expiresDate.getTime()) {
            return new String(ltpa.user);
        }

        return null;
    }

    /**
     * 将cookie封装到Map里面
     *
eddie.woo's avatar
eddie.woo committed
208
     * @param
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
     * @return
     * @method ReadCookieMap Create on 2018年6月29日 上午11:35:45
     * Copyright (c) 2018 by future-info.
     * @author caoj
     * @tel 15991758179
     * @mail caoj@landray.com.cn
     * @version 0.1
     */
//	public static Map<String, Cookie> ReadCookieMap(HttpServletRequest request) {
//		Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
//		Cookie[] cookies = request.getCookies();
//		if (null != cookies) {
//			for (Cookie cookie : cookies) {
//				cookieMap.put(cookie.getName(), cookie);
//			}
//		}
//		return cookieMap;
//	}
    public static void main(String[] args) {
        try {
            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            LtpaToken token = LtpaToken.generate("SuperAdmin", sd.parse("2018-11-28 00:00:00"), sd.parse("2018-12-27 23:59:59"));
            System.out.println("组装——" + token.toString());

//			System.out.println("解析登录名——" + LtpaToken.validate(token.toString()));
            System.out.println("解析登录名——" + LtpaToken.validate(token.toString()));
            //System.out.println(URLDecoder.decode("cookie=LtpaToken%3DAAECAzVCNEQ3NkQwNUI0RDc2RTkxMDM5MjX0gUNwIFvV2RqsWiPrETS2HCRERA%3D%3D&url=http%3A%2F%2Foa%2Ech%2Ecom%2Ecn%3A8080%2Fekp%2Fkm%2Fcarmng%2Eindex", "utf-8"));
            System.out.println(URLEncoder.encode("LtpaToken=" + token.toString()));
            //http://kk.ch.com.cn:8000/serverj/forward?domanId=3&cookie=LtpaToken%3DAAECAzVCNENDMTAwNUI0RTEyN0YxMDM5MjawmMtC7Et4uESvZgLgSuBaoaejKQ%3D%3D&url=http%3A%2F%2Foa%2Ech%2Ecom%2Ecn%3A8080%2Fekp%2Fkm%2Fcarmng%2Eindex

        } catch (Exception e) {
            e.printStackTrace();
            // TODO: handle exception
        }
    }

    public Date getExpiresDate() {
        return expiresDate;
    }

    public void setExpiresDate(Date expiresDate) {
        this.expiresDate = expiresDate;
    }


}