1
votes

My objective is to encrypt data in Iphone and decrypt it on java server.

I am using Symmetric encryption .

I have generated the key using KeyGenerator at the java side.

code for generating key is as follows:

//Java Code for key generation

File keyFile = new File("F:/key","mykey.key");
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
SecretKey skey = kgen.generateKey();
byte[] enc= skey.getEncoded();
FileUtils.writeStringToFile(keyFile ,Base64.encodeBase64String(enc),"UTF-8");   

Following is the java code for decryption:

//get key from file

File file = new File("F:/key", "mykey.key");
    SecretKeySpec keySpec= null;
try {
    byte[] keyBytes = Base64.decodeBase64(FileUtils.readFileToString(file,"UTF-8"));
     keySpec= new SecretKeySpec(keyBytes, 0, 16, "AES");
     byte[] raw = keySpec.getEncoded();

} catch (Exception e) {
    e.printStackTrace();
}

//Decrypt String encryptedString(from Iphone)

byte[] tempByte = Base64.decodeBase64(encryptedString);

Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] cipherData = cipher.doFinal(tempByte);

String ttt = new String(cipherData ,"UTF-8");
System.out.println(ttt);

And the iphone code is similar to th code given in following link: Encrypting data with Objective-C and decrypt it with Java Problem

I am getting the following exception while decrypting in java.

javax.crypto.BadPaddingException: Given final block not properly padded

Please help...

1

1 Answers

2
votes

Well the padding and mode has to match. If you copied the Objective-C code, then the ciphertext on the Objective-C side has the ECB mode and the PKCS7 padding.

By default the java AES cipher has the CBC mode and PKCS5 padding (though I'm not sure, and AFAIK PKCS5 and PKCS7 are somewhat compatible). I guess you have to specify these explicitly. Those settings have to match otherwise something goes wrong. So you have to create the cipher like that:

Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

Btw. if you can choose the encryption-mode you should use CBC (but then on both sides).