You may get InvalidKeyException: Parameters missing error while performing AES encryption or decryption for password or any sensitive information. The exception stack trace look like this:
Error while decrypting: java.security.InvalidKeyException: Parameters missing
Solution to InvalidKeyException
Use IvParameterSpec
class which specifies an initialization vector (IV). An initialization vector is necessary for any cipher in any feedback mode, e.g. CBC.
private static String secretKey = "boooooooooom!!!!"; private static String salt = "ssshhhhhhhhhhh!!!!"; public static String decrypt(String strToDecrypt, String secret) { try { byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; IvParameterSpec ivspec = new IvParameterSpec(iv); SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), salt.getBytes(), 65536, 256); SecretKey tmp = factory.generateSecret(spec); SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); cipher.init(Cipher.DECRYPT_MODE, secretKey, ivspec); return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt))); } catch (Exception e) { System.out.println("Error while decrypting: " + e.toString()); } return null; }
Happy Learning !!
Leave a Reply