AES-128 CBC Pk5 result differs with Android code

AES 128 CBC algorithm is not producing same results compared to Android code. We have all static strings for key, iv and salt, even then the IV we couldnt match and produce same output as android.

This is the Android code,

object AESEncyption {
​
    fun encrypt(strToEncrypt: String) :  String?
    {
        try
        {
            val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
            val factory =
                SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1")
            val spec: KeySpec = PBEKeySpec(secretKey.toCharArray(), hex(salt), iterationCount, keySize)
            val key: SecretKey = SecretKeySpec(factory.generateSecret(spec).encoded, "AES")
            cipher.init(Cipher.ENCRYPT_MODE, key, IvParameterSpec(hex(iv)))
​
            return base64(cipher.doFinal(strToEncrypt.toByteArray(Charsets.UTF_8)))
        }
        catch (e: Exception)
        {
            Log.i("Him","Error while encrypting: $e")
        }
        return null
    }
​
    private fun base64(bytes: ByteArray?): String {
        return android.util.Base64.encodeToString(bytes, android.util.Base64.DEFAULT)
    }
​
  /*  fun base64(str: String?): ByteArray? {
        return Base64.decodeBase64(str)
    }*/
​
    fun hex(bytes: ByteArray?): String? {
        return Hex.encodeHexString(bytes)
    }
​
    fun hex(str: String): ByteArray? {
        return try {
            Hex.decodeHex(str.toCharArray())
        } catch (e: DecoderException) {
            throw IllegalStateException(e)
        }
    }
}

iOS code is

 let enc = try AES(key: keyVar2!.bytes, blockMode: CBC(iv: iv.base64FromHex.ivToUInt8Array), padding: .pkcs5).encrypt(value.bytes)
            let encryptedData = Data(enc)
  • This is the IV value for comparison,

    Android Value = [-14, 125, 92, -103, 39, 114, 107, -50, -2, 117, 16, -79, -67, -45, -47, 55] ios value = [242, 125, 92, 153, 39, 114, 107, 206, 254, 117, 16, 177, 189, 211, 209, 55]

    Only this is different, hence we are getting different encrypted value. Any solution for this?

Add a Comment

Replies

Apple CryptoKit doesn’t Support CBC mode; it only supports GCM. I’m not sure where the AES type you’re working with comes from, but it’s not an Apple API.

As to how you should proceed here, I recommend that you take a look at the CryptoCompatibility sample code. This shows how to use our AES CBC API, Common Crypto, to generate results that line up with various other platforms.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"