Guest User

Untitled

a guest
Mar 22nd, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. import static org.apache.commons.lang3.StringUtils.isBlank;
  2.  
  3. import java.util.Base64;
  4.  
  5. import javax.crypto.Cipher;
  6. import javax.crypto.spec.IvParameterSpec;
  7. import javax.crypto.spec.SecretKeySpec;
  8.  
  9. /**
  10. * Helper encryption function.
  11. */
  12. public 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. }
Add Comment
Please, Sign In to add comment