Decrypted String总是返回Null

时间:2017-10-11 18:20:16

标签: swift xcode macos encryption

使用

从服务器获取数据
   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
}

使用

解密
responseString

即使optional("")不为null,也会返回以下代码 let unencode = String(describing: responseString!).aesDecrypt(key: "123456789012asdsadasd", iv: "iv-salt-string--")

document.getElementById('email').setAttribute('value', localStorage.getItem('email'));

为什么会这样?请指教。

1 个答案:

答案 0 :(得分:1)

Per MartinR的评论:

  

我已经确认“JDoNBXk21oJ9x15Bkv12uw ==”正是使用您的密钥和iv加密空字符串的结果。错误发生在PHP脚本中,而不是Swift代码中。

因此,您需要解决服务器上的错误。