· 9 years ago · Nov 30, 2016, 04:12 PM
1package lv.org.substance.crypt
2
3import java.security.spec.AlgorithmParameterSpec;
4import java.security.spec.KeySpec;
5
6import javax.crypto.Cipher;
7import javax.crypto.SecretKey;
8import javax.crypto.SecretKeyFactory;
9import javax.crypto.spec.PBEKeySpec;
10import javax.crypto.spec.PBEParameterSpec;
11
12import org.apache.commons.codec.binary.Base64;
13
14public class EncryptionUtil
15{
16 // some random salt
17 private static final byte[] SALT = { (byte) 0x21, (byte) 0x21, (byte) 0xF0, (byte) 0x55, (byte) 0xC3, (byte) 0x9F, (byte) 0x5A, (byte) 0x75 };
18
19 private final static int ITERATION_COUNT = 31;
20
21 private EncryptionUtil()
22 {
23 }
24
25 public static String encode(String input)
26 {
27 if (input == null)
28 {
29 throw new IllegalArgumentException();
30 }
31 try
32 {
33
34 KeySpec keySpec = new PBEKeySpec(null, SALT, ITERATION_COUNT);
35 AlgorithmParameterSpec paramSpec = new PBEParameterSpec(SALT, ITERATION_COUNT);
36
37 SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
38
39 Cipher ecipher = Cipher.getInstance(key.getAlgorithm());
40 ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
41
42 byte[] enc = ecipher.doFinal(input.getBytes());
43
44 String res = new String(Base64.encodeBase64(enc));
45 // escapes for url
46 res = res.replace('+', '-').replace('/', '_').replace("%", "%25").replace("\n", "%0A");
47
48 return res;
49
50 }
51 catch (Exception e)
52 {
53 }
54
55 return "";
56
57 }
58
59 public static String decode(String token)
60 {
61 if (token == null)
62 {
63 return null;
64 }
65 try
66 {
67
68 String input = token.replace("%0A", "\n").replace("%25", "%").replace('_', '/').replace('-', '+');
69
70 byte[] dec = Base64.decodeBase64(input.getBytes());
71
72 KeySpec keySpec = new PBEKeySpec(null, SALT, ITERATION_COUNT);
73 AlgorithmParameterSpec paramSpec = new PBEParameterSpec(SALT, ITERATION_COUNT);
74
75 SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
76
77 Cipher dcipher = Cipher.getInstance(key.getAlgorithm());
78 dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
79
80 byte[] decoded = dcipher.doFinal(dec);
81
82 String result = new String(decoded);
83 return result;
84
85 }
86 catch (Exception e)
87 {
88 // use logger in production code
89 e.printStackTrace();
90 }
91
92 return null;
93 }
94
95}