private byte[] crypt(@NotNull String cipherAlgorithm, @NotNull java.security.Key key, @NotNull byte[] data, boolean encrypt) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { try { Cipher cipher = Cipher.getInstance(cipherAlgorithm); if (cipherAlgorithm.startsWith("AES/CBC")) { if (encrypt) { byte[] iv = CryptoUtils.genSalt(16); cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv)); final byte[] encryptedData = cipher.doFinal(data); return ArrayUtils.concat(iv, encryptedData); } else { CryptoUtils.DataAndSalt dataAndSalt = CryptoUtils.splitSalt(data, 16); cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(dataAndSalt.getSalt())); return cipher.doFinal(dataAndSalt.getData()); } } else { cipher.init(encrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, key); return cipher.doFinal(data); } } catch (InvalidAlgorithmParameterException e) { throw new UnexpectedException(e); } }