aes 128 message decryption — Swift, iOS

℡╲_俬逩灬. 提交于 2019-12-02 18:19:09

问题


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.

Key-value and message-value are base64Url.

Usage:

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

Swift 2.3


回答1:


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.



来源:https://stackoverflow.com/questions/43453556/aes-128-message-decryption-swift-ios

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