简体   繁体   English

aes 128消息解密-Swift,iOS

[英]aes 128 message decryption — Swift, iOS

I'm trying to decrypt message with 128 key with following code. 我正在尝试使用以下代码解密带有128键的消息。 This is an extension for String: 这是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. 对于输入向量(iv),我使用nil值。 There is crypData is exist but I can't read this properly and unencryptedMessage is nil as well. 有crypData存在,但我无法正确读取它, unencryptedMessage也为零。 Online tools notifies that data is incorrect, but on backend-side it works fine. 联机工具会通知数据不正确,但是在后端,它可以正常工作。

Key-value and message-value are base64Url. 键值和消息值是base64Url。

Usage: 用法:

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

Swift 2.3 迅捷2.3

As Rob said, the main issue was input data. 正如Rob所说,主要问题是输入数据。 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. 对我来说是UTF-8。 Also, you should check key length. 另外,您应该检查密钥长度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM