package app.utils; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Base64; public class CryptoMethods { public static final String algorithm = "AES/CBC/PKCS5Padding"; public static String generateIv() { byte[] iv = new byte[16]; new SecureRandom().nextBytes(iv); return convertIvToString(new IvParameterSpec(iv)); } public static String generateKey(int n){ try { KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(n); SecretKey key = keyGenerator.generateKey(); return convertSecretKeyToString(key); } catch (Exception e) { e.printStackTrace(); return null; } } public static String convertSecretKeyToString(SecretKey secretKey) throws NoSuchAlgorithmException { byte[] rawData = secretKey.getEncoded(); return Base64.getEncoder().encodeToString(rawData); } public static String convertIvToString(IvParameterSpec iv) { byte[] rawData = iv.getIV(); return Base64.getEncoder().encodeToString(rawData); } public static SecretKey convertStringToSecretKeyto(String encodedKey) { byte[] decodedKey = Base64.getDecoder().decode(encodedKey); return new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES"); } public static IvParameterSpec convertStringToIv(String iv) { byte[] decodedIv = Base64.getDecoder().decode(iv); return new IvParameterSpec(decodedIv, 0, decodedIv.length); } public static String encrypt(String input, String key, String iv) { return encrypt(algorithm, input, convertStringToSecretKeyto(key), convertStringToIv(iv)); } public static String encrypt(String algorithm, String input, String key, String iv) { return encrypt(algorithm, input, convertStringToSecretKeyto(key), convertStringToIv(iv)); } public static String encrypt(String algorithm, String input, SecretKey key, IvParameterSpec iv) { try { Cipher cipher = Cipher.getInstance(algorithm); cipher.init(Cipher.ENCRYPT_MODE, key, iv); byte[] cipherText = cipher.doFinal(input.getBytes()); return Base64.getEncoder() .encodeToString(cipherText); } catch (Exception e) { return null; } } public static String decrypt(String cipherText, String key, String iv) { return decrypt(algorithm, cipherText, convertStringToSecretKeyto(key), convertStringToIv(iv)); } public static String decrypt(String algorithm, String cipherText, String key, String iv) { return decrypt(algorithm, cipherText, convertStringToSecretKeyto(key), convertStringToIv(iv)); } public static String decrypt(String algorithm, String cipherText, SecretKey key, IvParameterSpec iv) { try { Cipher cipher = Cipher.getInstance(algorithm); cipher.init(Cipher.DECRYPT_MODE, key, iv); byte[] plainText = cipher.doFinal(Base64.getDecoder() .decode(cipherText)); return new String(plainText); } catch (Exception e) { return null; } } }