Home:ALL Converter>iOS 13/Swift 5 Encryption/Decryption problem with Commoncrypto

iOS 13/Swift 5 Encryption/Decryption problem with Commoncrypto

Ask Time:2019-11-08T20:04:45         Author:Vasu

Json Formatter

I am using CommonCrypto with AES128/CBC/PKCS7Padding for encryption/decryption.

AES encryption in swift

Referred to the above link, code working fine for below iOS 13 version, but not working for iOS version 13 and above. Please suggest a working solution for iOS 13.Thanks in advance.

func aesDecrypt(key:String, iv:String, options:Int = kCCOptionPKCS7Padding) -> String?
{

    if let keyData = key.data(using: String.Encoding.utf8),
        let data = NSData(base64Encoded: self, options: .ignoreUnknownCharacters),
        let cryptData    = NSMutableData(length: Int((data.length)) + kCCBlockSizeAES128)
    {
        let keyLength              = size_t(kCCKeySizeAES128)
        let operation: CCOperation = UInt32(kCCDecrypt)
        let algoritm:  CCAlgorithm = UInt32(kCCAlgorithmAES128)
        let options:   CCOptions   = UInt32(options)

        var numBytesEncrypted :size_t = 0

        let cryptStatus = CCCrypt(operation,
                                  algoritm,
                                  options,
                                  (keyData as NSData).bytes, keyLength,
                                  iv,
                                  data.bytes, data.length,
                                  cryptData.mutableBytes, cryptData.length,
                                  &numBytesEncrypted)

        if UInt32(cryptStatus) == UInt32(kCCSuccess) {
            cryptData.length = Int(numBytesEncrypted)
            let unencryptedMessage = String(data: cryptData as Data, encoding:String.Encoding.utf8)
            print("Decrypt Result unencryptedMessage:::",unencryptedMessage as Any)
            return unencryptedMessage
        }
        else {
            print("\(UInt32(cryptStatus))")
            return nil
        }
    }
    else {
        Logger.log(message: "Faild to decrypt the string", event: .e) // Error
        return nil
    }
}

Author:Vasu,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/58766258/ios-13-swift-5-encryption-decryption-problem-with-commoncrypto
yy