简体   繁体   中英

Porting AES Encryption from Java to Objective-C

I was tasked to port AES encryption from Java to Objective-C. I don't have access to the server's code where decryption took place. Using FBEncryptor , I've managed to do a simple AES encrypt of a string in Objective-C and decrypted it in Java and vice versa.

However, when I tried to send an encrypted data in Objective-C to server (which again, I don't have access to), the server sent me an "DER input not an octet string" fault. I figured that this code in Java, which I cannot replicate in Objective-C that is holding my path to success in the task.

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, sKey);
String ivBase64 = Base64.encodeBytes(cipher.getParameters().getEncoded());

The ivBase64 was sent to the server along with the encrypted String.

Any help in how to port this little part cipher.getParameters().getEncoded() to Objective-C is very much appreciated.

Thanks.

What is happening is that the cipher.getParameters() call returns an instance of AlgorithmParameters . This instance has a method getEncoded() that has the following description:

Returns the parameters in their primary encoding format. The primary encoding format for parameters is ASN.1, if an ASN.1 specification for this type of parameters exists.

Now, as far as I know, there is no such thing as a default ASN.1 DER encoding for an IV, but since an IV is basically a byte array, the most logical ASN.1 encoding is the OCTET STRING. When DER encoded, this ASN.1 type has a tag with value 04h and then the length. The length will always the size of the IV directly encoded a single byte. The IV will always have the size of the block of the underlying cipher, which is always 16 bytes for AES.

So finally, you should be OK by prepending the bytes valued 04h and 10h to the IV.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM