· 7 years ago · Jan 10, 2019, 09:26 PM
1import java.io.IOException;
2import java.io.UnsupportedEncodingException;
3import java.nio.charset.StandardCharsets;
4import java.security.InvalidKeyException;
5import java.security.NoSuchAlgorithmException;
6import java.util.regex.Matcher;
7import java.util.regex.Pattern;
8
9import javax.crypto.BadPaddingException;
10import javax.crypto.Cipher;
11import javax.crypto.IllegalBlockSizeException;
12import javax.crypto.NoSuchPaddingException;
13import javax.crypto.spec.SecretKeySpec;
14
15import org.apache.commons.codec.binary.Base64;
16
17public class EncryptionTool {
18
19 private final int length;
20 private final SecretKeySpec secretKey;
21 private final Cipher cipher;
22
23 public EncryptionTool() {
24 this("defaultSecret@123456789", 16);
25 }
26
27 public EncryptionTool(String secret, int length) {
28 try{
29 this.length = length;
30 byte[] key = new byte[length];
31 key = fixSecret(secret);
32 this.secretKey = new SecretKeySpec(key, "AES");
33 this.cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
34 }catch(Exception e){
35 throw new RuntimeException(e);
36 }
37 }
38
39 private byte[] fixSecret(String s) throws UnsupportedEncodingException {
40 if (s.length() < length) {
41 int missingLength = length - s.length();
42 for (int i = 0; i < missingLength; i++) {
43 s += " ";
44 }
45 }
46 return s.substring(0, length).getBytes(StandardCharsets.UTF_8.name());
47 }
48
49 private String encrypt(String input) {
50 try{
51 this.cipher.init(Cipher.ENCRYPT_MODE, this.secretKey);
52 return Base64.encode(cipher.doFinal(input.getBytes(StandardCharsets.UTF_8.name())));
53 }catch(Exception e){
54 throw new RuntimeException(e);
55 }
56 }
57
58 private String decrypt(String input) {
59 try{
60 this.cipher.init(Cipher.DECRYPT_MODE, this.secretKey);
61 byte[] encrypted = Base64.decode(input);
62 byte[] decrypted = this.cipher.doFinal(encrypted);
63 return new String(decrypted, StandardCharsets.UTF_8.name()).trim();
64 }catch(Exception e){
65 throw new RuntimeException("Unable to decrypt string " + input, e);
66 }
67 }
68
69 private static final Pattern ENCPASSWORD = Pattern.compile("ENC\\((.+?)\\)");
70
71 public String getEncryptedPassword(String input) {
72 return "ENC(" + encrypt(input) + ")";
73 }
74
75 public String getDecryptedPassword(String input) {
76 Matcher m = ENCPASSWORD.matcher(input);
77 if(m.matches()){
78 return decrypt(m.group(1));
79 }else{
80 return input;
81 }
82 }
83}