AES Decryption in SWIFT4 Producing null Value

匿名 (未验证) 提交于 2019-12-03 01:22:02

问题:

I'm using an extension method to decrypt a string which is encrypted by the server side php script using AES Algorithm.

The following is the extension method used

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)                 return unencryptedMessage             }             else {                 return nil             }         }         return nil     } 

This sometimes returns a null value

unencode = responseString?.aesDecrypt(key: "mykey", iv: "value"); 

I cannot figure out the exact reason why this happens.The responseString was not null when this happened.

Please advice

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!