I am stuck with a problem with AES Decryption in my android Application. I have searched a lot but unable to get the solution.
Here are the steps, what i am doing.
- Encrypt the credit card number with my key send to the Web server.
- Web server Decrypt the credit card number and save it.
- When we fetch the credit card number from the Web service.
- Then web server encrypt the credit card number with the same key and send to Us.
- Now When we decrypt this number, it throws bad padding exception for some credit card number information.
Also encrypted information is not same coming from the server, what we have send in encrypted format. While the same thing is done in iPhone app, and iPhone is able to decrypt the information successfully.
I am using the following code for encryption and decryption.
public class AES256Cipher {
public static byte[] ivBytes = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
public static String AES_Encode(String str, String key) throws java.io.UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
byte[] textBytes = str.getBytes("UTF-8");
AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
SecretKeySpec newKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = null;
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
return Base64.encodeToString(cipher.doFinal(textBytes), 0);
}
public static String AES_Decode(String str, String key) throws java.io.UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
byte[] textBytes =Base64.decode(str,0);
//byte[] textBytes = str.getBytes("UTF-8");
AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
SecretKeySpec newKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);
return new String(cipher.doFinal(textBytes), "UTF-8");
}
Please suggest.
EDIT: I one more thing, it is working for < 16 digits information. When we put the 16 digit information, then it is throwing the Exception in decryption.