Decrypting Data to String Conversion failure
Development environment: Xcode 15.4, macOS 14.7
Run-time configuration: iOS 15.8.1 & 16.0.1
DESCRIPTION OF PROBLEM
We were using objective C implementation of CCCrypt(see below) in our app earlier which we migrated to swift implementation recently. We convert the byte array that CCCrypt returns into Data, and data to string to read the decrypted value. It works perfectly fine in Objective C, whereas with new swift implementation this conversion is failing, it looks like CCCrypt is returning byte array with few non UTF8 characters and that conversion is failing in swift since Objective C is more tolerant with this conversion and converts the byte array to Data and then to string even though there are few imperfect UTF characters in the array.
Objective C
CCCryptorStatus CCCrypt(
CCOperation op, /* kCCEncrypt, etc. /
CCAlgorithm alg, / kCCAlgorithmAES128, etc. /
CCOptions options, / kCCOptionPKCS7Padding, etc. */
const void *key,
size_t keyLength,
const void iv, / optional initialization vector */
const void dataIn, / optional per op and alg */
size_t dataInLength,
void dataOut, / data RETURNED here */
size_t dataOutAvailable,
size_t *dataOutMoved)
API_AVAILABLE(macos(10.4), ios(2.0));
Swift Code
CCCrypt(_ op: CCOperation,
_ alg: CCAlgorithm,
_ options: CCOptions,
_ key: UnsafeRawPointer!,
_ keyLength: Int, _ iv: UnsafeRawPointer!,
_ dataIn: UnsafeRawPointer!,
_ dataInLength: Int,
_ dataOut: UnsafeMutableRawPointer!,
_ dataOutAvailable: Int,
_ dataOutMoved: UnsafeMutablePointer!) -> CCCryptorStatus
Data to String Conversion
String(data: decryptedData, encoding: .utf8)
STEPS TO REPRODUCE
Able to reproduce on below devices
iPhone - 7
OS Version 15.8.1
iPhone 14- Pro
OS Version 16.0.2
iPhone 15
iOS 18.0.1
**Decryption method return "Data" and converting into string using ".utf8" but String conversion is failing on above devices and some other devices as well. Decryption failure not occurring always.
**
Below code used for String conversion
String(data: decryptedData, encoding: .utf8)