/** * Decrypts the given input data. * * @param in data to decrypt * @param k secret key * @param a encryption algorithm * @param ivl initialization vector length * @return decrypted data * @throws NoSuchAlgorithmException ex * @throws NoSuchPaddingException ex * @throws InvalidKeyException ex * @throws InvalidAlgorithmParameterException ex * @throws IllegalBlockSizeException ex * @throws BadPaddingException ex */ private static byte[] decrypt(final byte[] in, final byte[] k, final byte[] a, final int ivl) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { final SecretKeySpec keySpec = new SecretKeySpec(k, string(a)); final Cipher cipher = Cipher.getInstance(string(ALGN.get(lc(a)))); // extract iv from message beginning final byte[] iv = substring(in, 0, ivl); final IvParameterSpec ivspec = new IvParameterSpec(iv); cipher.init(Cipher.DECRYPT_MODE, keySpec, ivspec); return cipher.doFinal(substring(in, ivl, in.length)); }
/** * Encrypts the given input data. * * @param in input data to encrypt * @param k key * @param a encryption algorithm * @param ivl initialization vector length * @return encrypted input data * @throws InvalidKeyException ex * @throws InvalidAlgorithmParameterException ex * @throws NoSuchAlgorithmException ex * @throws NoSuchPaddingException ex * @throws IllegalBlockSizeException ex * @throws BadPaddingException ex */ private static byte[] encrypt(final byte[] in, final byte[] k, final byte[] a, final int ivl) throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { final Cipher cipher = Cipher.getInstance(string(ALGN.get(lc(a)))); final SecretKeySpec kspec = new SecretKeySpec(k, string(a)); // generate random iv. random iv is necessary to make the encryption of a // string look different every time it is encrypted. final byte[] iv = new byte[ivl]; // create new random iv if encrypting final SecureRandom rand = SecureRandom.getInstance("SHA1PRNG"); rand.nextBytes(iv); final IvParameterSpec ivspec = new IvParameterSpec(iv); // encrypt/decrypt cipher.init(Cipher.ENCRYPT_MODE, kspec, ivspec); final byte[] t = cipher.doFinal(in); // initialization vector is appended to the message for later decryption return concat(iv, t); }