01: package de.schlund.pfixcore.example.bank;
02:
03: import java.security.NoSuchAlgorithmException;
04:
05: import javax.crypto.Cipher;
06: import javax.crypto.KeyGenerator;
07: import javax.crypto.SecretKey;
08:
09: import sun.misc.BASE64Decoder;
10: import sun.misc.BASE64Encoder;
11: import de.schlund.pfixxml.util.MD5Utils;
12:
13: public class AuthTokenManager {
14:
15: private static SecretKey secretKey;
16: private static Object keyLock = new Object();
17: private static long keyLifeTime = 60 * 60 * 1000;
18: private static long keyGenTime = 0;
19: private static String signKey = "j45Nh&$jd§Jd99(z";
20:
21: public static String[] decodeAuthToken(String str) {
22: String decStr = decrypt(str);
23: String[] parts = decStr.split(":");
24: if (parts.length < 2)
25: throw new IllegalArgumentException("No values found.");
26: String[] values = new String[parts.length - 1];
27: for (int i = 0; i < values.length; i++)
28: values[i] = parts[i];
29: return values;
30: }
31:
32: public static String createAuthToken(String[] values) {
33: StringBuilder sb = new StringBuilder();
34: for (String value : values) {
35: sb.append(value);
36: sb.append(":");
37: }
38: String hash = MD5Utils.hex_md5(sb.toString() + signKey, "utf8");
39: String token = sb.toString() + hash;
40: String encToken = encrypt(token);
41: return encToken;
42: }
43:
44: private static SecretKey getSecretKey() {
45: synchronized (keyLock) {
46: if (secretKey == null
47: || (System.currentTimeMillis() - keyLifeTime) > keyGenTime) {
48: try {
49: KeyGenerator keyGen = KeyGenerator
50: .getInstance("DES");
51: secretKey = keyGen.generateKey();
52: keyGenTime = System.currentTimeMillis();
53: } catch (NoSuchAlgorithmException x) {
54: throw new RuntimeException("Can't generate key.", x);
55: }
56: }
57: return secretKey;
58: }
59: }
60:
61: private static String encrypt(String str) {
62: try {
63: SecretKey key = getSecretKey();
64: Cipher desCipher = Cipher
65: .getInstance("DES/ECB/PKCS5Padding");
66: desCipher.init(Cipher.ENCRYPT_MODE, key);
67: byte[] cleartext = str.getBytes("UTF-8");
68: byte[] ciphertext = desCipher.doFinal(cleartext);
69: BASE64Encoder enc = new BASE64Encoder();
70: return enc.encode(ciphertext);
71: } catch (Exception x) {
72: throw new RuntimeException("Encrypting token failed.", x);
73: }
74: }
75:
76: private static String decrypt(String base64Str) {
77: try {
78: SecretKey key = getSecretKey();
79: BASE64Decoder dec = new BASE64Decoder();
80: byte[] ciphertext = dec.decodeBuffer(base64Str);
81: Cipher desCipher = Cipher
82: .getInstance("DES/ECB/PKCS5Padding");
83: desCipher.init(Cipher.DECRYPT_MODE, key);
84: byte[] cleartext = desCipher.doFinal(ciphertext);
85: String str = new String(cleartext, "UTF-8");
86: return str;
87: } catch (Exception x) {
88: throw new RuntimeException("Decrypting token failed.", x);
89: }
90: }
91:
92: }
|