Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import static org.apache.commons.lang3.StringUtils.isBlank;
- import java.util.Base64;
- import javax.crypto.Cipher;
- import javax.crypto.spec.IvParameterSpec;
- import javax.crypto.spec.SecretKeySpec;
- /**
- * Helper encryption function.
- */
- public class EncryptUtils {
- private final static String KEY = "AWTyTh4cjqo5uMdXb0JHkj2q0xf719uE";
- private final static String ALGO = "AES/CBC/PKCS5Padding";
- public static String encrypt(String clearTxt) {
- if (isBlank(clearTxt)) {
- throw new IllegalArgumentException("Impossible to encrypt an empty string");
- }
- try {
- final SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(), "AES");
- Cipher cipher = Cipher.getInstance(ALGO);
- cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(new byte[16]));
- byte[] encrypted = cipher.doFinal(clearTxt.getBytes());
- return Base64.getEncoder().encodeToString(encrypted);
- } catch (Exception e) {
- throw new SecurityException("Something went wrong with the encrypt function...", e);
- }
- }
- public static String decrypt(String encryptedTxt) {
- if (isBlank(encryptedTxt)) {
- throw new IllegalArgumentException("Impossible to decrypt an empty string");
- }
- try {
- final SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(), "AES");
- Cipher cipher = Cipher.getInstance(ALGO);
- cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(new byte[16]));
- byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(encryptedTxt));
- return new String(decrypted);
- } catch (Exception e) {
- throw new SecurityException("Something went wrong with the decrypt function...", e);
- }
- }
- }
Add Comment
Please, Sign In to add comment