1

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 Answer 1

2

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).

Sign up to request clarification or add additional context in comments.

2 Comments

PKCS5 and PKCS7 are indeed compatible. ECB mode is insecure and should not be used, use CTR or CBC mode instead. Your advice to explicitly specify the padding to be used at both ends is correct.
Actually the problem was in the key. I had encoded the key while saving the file. And In Phone I was using the encoded key for encryption whereas in Java I was using the original key for decryption. Thanks for your time!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.