aes 128消息解密 - Swift,iOS [英] aes 128 message decryption -- Swift, iOS

查看:225
本文介绍了aes 128消息解密 - Swift,iOS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用128个密钥解密消息,具有以下代码。这是String的扩展名:

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
}

对于输入向量(iv)我使用nil值。
有crypData存在但我无法正确读取, unencryptedMessage 也是无效的。在线工具通知数据不正确,但在后端方面工作正常。

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.

键值和消息值为base64Url。

Key-value and message-value are base64Url.

用法:

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

Swift 2.3

Swift 2.3

推荐答案

正如Rob所说,主要问题是输入数据。所以,我已经将消息和密钥转换为十六进制值。如果您遇到同样的问题,请确保客户端和后端的值具有相同的编码参数。对我而言是UTF-8。
此外,您应该检查密钥长度。

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.

这篇关于aes 128消息解密 - Swift,iOS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆