· 7 years ago · Mar 23, 2018, 02:58 AM
1import static org.apache.commons.lang3.StringUtils.isBlank;
2
3import java.util.Base64;
4
5import javax.crypto.Cipher;
6import javax.crypto.spec.IvParameterSpec;
7import javax.crypto.spec.SecretKeySpec;
8
9/**
10 * Helper encryption function.
11 */
12public class EncryptUtils {
13
14 private final static String KEY = "AWTyTh4cjqo5uMdXb0JHkj2q0xf719uE";
15 private final static String ALGO = "AES/CBC/PKCS5Padding";
16
17 public static String encrypt(String clearTxt) {
18 if (isBlank(clearTxt)) {
19 throw new IllegalArgumentException("Impossible to encrypt an empty string");
20 }
21
22 try {
23 final SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(), "AES");
24 Cipher cipher = Cipher.getInstance(ALGO);
25 cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(new byte[16]));
26 byte[] encrypted = cipher.doFinal(clearTxt.getBytes());
27 return Base64.getEncoder().encodeToString(encrypted);
28 } catch (Exception e) {
29 throw new SecurityException("Something went wrong with the encrypt function...", e);
30 }
31 }
32
33 public static String decrypt(String encryptedTxt) {
34 if (isBlank(encryptedTxt)) {
35 throw new IllegalArgumentException("Impossible to decrypt an empty string");
36 }
37
38 try {
39 final SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(), "AES");
40 Cipher cipher = Cipher.getInstance(ALGO);
41 cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(new byte[16]));
42 byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(encryptedTxt));
43 return new String(decrypted);
44 } catch (Exception e) {
45 throw new SecurityException("Something went wrong with the decrypt function...", e);
46 }
47 }
48}