· 9 years ago · Oct 07, 2016, 02:00 AM
1public class EncryptionUtil {
2
3 private static final byte[] SALT = {(byte) 0x21, (byte) 0x21, (byte) 0xF0, (byte) 0x55, (byte) 0xC3, (byte) 0x9F, (byte) 0x5A, (byte) 0x75};
4
5 private final static int ITERATION_COUNT = 31;
6
7 private EncryptionUtil() {
8 }
9
10 public static String encode(String input) {
11 if (input == null) {
12 throw new IllegalArgumentException();
13 }
14 try {
15
16 KeySpec keySpec = new PBEKeySpec(null, SALT, ITERATION_COUNT);
17 AlgorithmParameterSpec paramSpec = new PBEParameterSpec(SALT, ITERATION_COUNT);
18
19 SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
20
21 Cipher ecipher = Cipher.getInstance(key.getAlgorithm());
22 ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
23
24 byte[] enc = ecipher.doFinal(input.getBytes());
25
26 String res = new String(Base64.encodeBase64(enc));
27 // escapes for url
28 res = res.replace('+', '-').replace('/', '_').replace("%", "%25").replace("\n", "%0A");
29
30 return res;
31
32 } catch (Exception e) {
33 }
34
35 return "";
36
37 }
38
39 public static String decode(String token) {
40 if (token == null) {
41 return null;
42 }
43 try {
44
45 String input = token.replace("%0A", "\n").replace("%25", "%").replace('_', '/').replace('-', '+');
46
47 byte[] dec = Base64.decodeBase64(input.getBytes());
48
49 KeySpec keySpec = new PBEKeySpec(null, SALT, ITERATION_COUNT);
50 AlgorithmParameterSpec paramSpec = new PBEParameterSpec(SALT, ITERATION_COUNT);
51
52 SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
53
54 Cipher dcipher = Cipher.getInstance(key.getAlgorithm());
55 dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
56
57 byte[] decoded = dcipher.doFinal(dec);
58
59 String result = new String(decoded);
60 return result;
61
62 } catch (Exception e) {
63 // use logger in production code
64 e.printStackTrace();
65 }
66
67 return null;
68 }
69
70}