i work on KMM project android and iOS
code received data from PHP server that need to decode from AES Cipher
on Android code work but on ios i try to create this code on ios platfrom as kotlin code use objective -c for kmm
when i try use the code on ios not work only work on andrid
my code here on ios
@OptIn(ExperimentalForeignApi::class)
fun iosDecrypt(data: String, secretKey: String): String? {
val CIPHER_KEY_LEN = kCCKeySizeAES128.toInt()
//val CIPHER_IV_LEN = 16
val CIPHER_ALGORITHM = kCCAlgorithmAES128
val CIPHER_OPTIONS = kCCOptionPKCS7Padding
var key = secretKey
try {
if (key.length < CIPHER_KEY_LEN) {
val numPad: Int = CIPHER_KEY_LEN - key.length
for (i in 0 until numPad) {key += "0"
}
} else if (key.length > CIPHER_KEY_LEN) {
key = key.substring(0, CIPHER_KEY_LEN)
}
val parts = data.split(":")
val encryptedData = parts[0].base64Decoded.toByteArray().toNSData()//decodeBase64(parts[0])
val ivData =parts[1].base64Decoded.toByteArray().toNSData()// decodeBase64(parts[1])
println("iv = $ivData")
val keyDataByte = key.toByteArray(Charsets.ISO_8859_1)
println("keyDataByte :${keyDataByte.contentToString() }, bytes :${keyDataByte.size}")
val keyData = keyDataByte.toNSData()
println("keyData :$keyData , bytes :${keyData.length}")
val decryptedData = NSMutableData()
println("decryptedData:$decryptedData")
memScoped { // Use memScoped for memory allocation
val numBytesDecrypted = alloc<size_tVar>()
val status = CCCrypt(
kCCDecrypt,
CIPHER_ALGORITHM,
CIPHER_OPTIONS,
keyData.bytes,
kCCKeySizeAES128.toULong(),
ivData.bytes,
encryptedData.bytes,
(encryptedData.length.convert() ?: 0).toULong(),
decryptedData.mutableBytes,
decryptedData.length.convert(),
numBytesDecrypted.ptr
)
if (status == kCCSuccess) {
decryptedData.setLength( numBytesDecrypted.value.toULong())
return decryptedData.toString()
} else {
println("Decryption failed with status: $status")
return null
}
}
} catch (ex: Exception) {
ex.printStackTrace()
}
return null
}
@OptIn(ExperimentalForeignApi::class, BetaInteropApi::class)
fun ByteArray.toNSData(): NSData {
memScoped {
val data = this@toNSData
val pointer = data.usePinned {
it.addressOf(0)
}
return NSData.create(bytes = pointer, length = data.size.toULong())
}
}
there out Decryption failed with status :4301
this code build i don’t know where the problem of code
are there can other way to decode
iv and key and data i had sure on it be same of on android debug
and sure from decode64 for both