Search code examples
objective-cencryptioncryptographycommoncryptorncryptor

Decrypting AES in Objective C


I am new to encryption

The problem:

I am given a set of encrypted strings and I need to decrypt them to show to the mobile client user. For android, it decrypt fine and i am using the following method "decrypt". For iOS, I am having a lot of trouble translating this java method to Objective C. I have attempted using NSData+CommonCrypto, RNCryptor. Both of them will return some decrypted data, However when converted the decrypted data to string, it will always be nil.

Goal:

Translate the java decrypt method to Objective C(Decrypt a string in Objective C using a secrete key)

Any suggestions, comments, opinions, pseudo code would be greatly appreciated. thanks

Android Decrypt Method

public static String decrypt(String message){
    try {
        Cipher c = Cipher.getInstance("AES");
        SecretKeySpec key = new SecretKeySpec(secrKey.getBytes(), "AES");
        c.init(Cipher.DECRYPT_MODE, key);
        byte[] decordedValue = Base64.decode(message.getBytes(), Base64.DEFAULT);
        byte[] decValue = c.doFinal(decordedValue);
        String decryptedValue = new String(decValue);
        String decoded = new String(Base64.decode(decryptedValue, Base64.DEFAULT));
        return decoded;
    }catch(Exception e){
        return null;
    }
}

Solution

  • The Java getInstance method should provide all the necessary information and not rely on defaults. Such as: "AES/CBC/PKCS5Padding (128)", "AES/ECB/NoPadding (128)" or some other combination.

    With the "AES" spec I would guess: ECB mode (really bad choice), PKCS5Padding, and a key length based on the supplied key null padded as needed.

    See Class Cipher docs.