public classEncryptUtils {private static final String SECRET_KEY_1 = "YIORGA4dBYp6y7u8";private static final String SECRET_KEY_2 = "C6B8r5y7u7Uh37Sy";privateIvParameterSpec ivParameterSpec;privateSecretKeySpec secretKeySpec;privateCipher cipher;public EncryptUtils() throwsUnsupportedEncodingException, NoSuchPaddingException, NoSuchAlgorithmException {
ivParameterSpec= new IvParameterSpec(SECRET_KEY_1.getBytes("UTF-8"));
secretKeySpec= new SecretKeySpec(SECRET_KEY_2.getBytes("UTF-8"), "AES");
cipher= Cipher.getInstance("AES/CBC/PKCS5PADDING");
}/*** Encrypt the string with this internal algorithm.
*
*@paramtoBeEncrypt string object to be encrypt.
*@returnreturns encrypted string.
*@throwsNoSuchPaddingException
*@throwsNoSuchAlgorithmException
*@throwsInvalidAlgorithmParameterException
*@throwsInvalidKeyException
*@throwsBadPaddingException
*@throwsIllegalBlockSizeException*/
public String encrypt(String toBeEncrypt) throwsNoSuchPaddingException, NoSuchAlgorithmException,
InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);byte[] encrypted =cipher.doFinal(toBeEncrypt.getBytes());returnBase64.encodeBase64String(encrypted);
}/*** Decrypt this string with the internal algorithm. The passed argument should be encrypted using
* {@link#encrypt(String) encrypt} method of this class.
*
*@paramencrypted encrypted string that was encrypted using {@link#encrypt(String) encrypt} method.
*@returndecrypted string.
*@throwsInvalidAlgorithmParameterException
*@throwsInvalidKeyException
*@throwsBadPaddingException
*@throwsIllegalBlockSizeException*/
public String decrypt(String encrypted) throwsInvalidAlgorithmParameterException, InvalidKeyException,
BadPaddingException, IllegalBlockSizeException {
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);byte[] decryptedBytes =cipher.doFinal(Base64.decodeBase64(encrypted));return newString(decryptedBytes);
}
}