aes 128 message decryption — Swift, iOS

I’m trying to decrypt message with 128 key with following code. This is an extension for String:

func aesDecrypt(key:String, iv:String, options:Int = kCCOptionPKCS7Padding) -> String? {
    if let keyData = key.dataUsingEncoding(NSUTF8StringEncoding),
        data = NSData(base64EncodedString: self, options: .IgnoreUnknownCharacters),
        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.bytes, keyLength,
                                  nil,
                                  data.bytes, data.length,
                                  cryptData.mutableBytes, cryptData.length,
                                  &numBytesEncrypted)

        if UInt32(cryptStatus) == UInt32(kCCSuccess) {
            cryptData.length = Int(numBytesEncrypted)
            let unencryptedMessage = String(data: cryptData, encoding:NSUTF8StringEncoding)
            return unencryptedMessage
        }
        else {
            return nil
        }
    }
    return nil
}

For input vector (iv) I use nil value.
There is crypData is exist but I can’t read this properly and unencryptedMessage is nil as well. Online tools notifies that data is incorrect, but on backend-side it works fine.

  • AES128 encoding in iOS4+
  • CommonHMAC in Swift
  • Issue using CCCrypt (CommonCrypt) in Swift
  • Decrypting DES with CommonCrypto in Swift 3
  • Issue decrypting with CommonCrypto in Swift
  • How can I make my AES encryption identical between Java and Objective-C (iPhone)?
  • Key-value and message-value are base64Url.

    Usage:

    let decryptedMessage = message.aesDecrypt(keyTodecrypt, iv: nil)
    

    Swift 2.3

    Solutions Collect From Internet About “aes 128 message decryption — Swift, iOS”

    As Rob said, the main issue was input data. So, I have converted message and key to hex-value. If you have the same trouble, make sure that your value on client side and backend side has the same encoding parameter. For me it was UTF-8.
    Also, you should check key length.