· 8 years ago · Jan 31, 2018, 11:36 AM
1private Cipher getCipher(String encryptionKey, int cipherMode)
2 throws Exception {
3 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", new BouncyCastleProvider());
4 byte[] keys = Base64.decodeBase64(encryptionKey);
5 SecretKey speckey = new SecretKeySpec(keys, "AES");
6 byte[] ivParam = new byte[cipher.getBlockSize()];
7 System.arraycopy(speckey.getEncoded(), 0, ivParam, 0, ivParam.length);
8 cipher.init(cipherMode, speckey, new IvParameterSpec(ivParam));
9 return cipher;
10 }
11
12public String encryptWithGivenAESKey(String clearText, String AESKey) throws Exception {
13 Cipher cipher = getCipher(AESKey, Cipher.ENCRYPT_MODE);
14 byte[] encryptedBytes = cipher.doFinal(clearText.getBytes("UTF-8"));
15
16 return Base64.encodeBase64String(encryptedBytes);
17 }
18
19public String decryptWithGivenAESKey(String cipherTextBase64, String AESKey) throws Exception {
20 Cipher cipher = getCipher(AESKey, Cipher.DECRYPT_MODE);
21 byte[] inputBytes = Base64.decodeBase64(cipherTextBase64.getBytes());
22 byte[] encryptedBytes = cipher.doFinal(inputBytes);
23 return new String(encryptedBytes);
24 }