错误:致命错误:'试试!'表达式意外地引发了一个错误:CryptoSwift.AES.Error.BlockSizeExceeded:
我使用了这个AES https://github.com/krzyzanowskim/CryptoSwift和我的代码:
覆盖func viewDidLoad(){ super.viewDidLoad()
let jsonString = "{ \"device\": \"iphone\", \"req\": \"connect\", \"deviceId\": \"device ID\" }";
let url = UrlManager()
url.setRequestData(jsonString)
url.sendRequest({ (response) -> Void in
print("Response data: \(response)")
let bytes: [UInt8] = Converter.hexstringConvertToBytes(response)
print("Bytes: \(bytes)")
let dencryptedBytes: [UInt8] = try! bytes.decrypt(AES(key: UrlManager.CONNECTION_KEY, iv: UrlManager.CONNECTION_IV))
print("Decoded Bytes: \(dencryptedBytes)")
let jsonData: String = Converter.bytesConvertToString(dencryptedBytes)
print("Received json: \(jsonData)")
})
UrlManager的方法:
internal func sendRequest(responseHandler :( response:String) - > Void){
SocketManager.sharedInstance.sendMessage(self.requestData, handler: responseHandler)
}
SocketManager方法:
internal func sendMessage(message:String,handler:(response:String) - > Void){
let qualityOfServiceClass = QOS_CLASS_BACKGROUND
let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
dispatch_async(backgroundQueue, {
// set response data to UrlManager
let response = self.sendRequest(message, client: self.socket)
handler(response: response!)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
//print("This is run on the main queue")
})
})
}
但这是工作(当我测试此代码时):
让hexaString =“0B8F665884EE009C64A64862E26D33C42F490D6EF227709B1900D42B71FB2169802A27FACDCF2D5587A468E2AE0C14FD7FFC2D0D291A0021814A2D5EA4DC1225BE64B04C8CCA831CB1C97277040F5E36”
var numbers = [UInt8]()
var from = hexaString.startIndex
while from != hexaString.endIndex {
let to = from.advancedBy(2, limit: hexaString.endIndex)
numbers.append(UInt8(hexaString[from ..< to], radix: 16) ?? 0)
from = to
}
print(numbers) // [215, 193, 122, 79]
let dencryptedBytes: [UInt8] = try! numbers.decrypt(AES(key: "be8d5ba39cde4e41", iv: "a5e5ff5dcd2a655c"))
print(dencryptedBytes)
if let str = NSString(bytes: dencryptedBytes, length: dencryptedBytes.count, encoding: NSUTF8StringEncoding) as? String {
print(str)
} else {
print("not a valid UTF-8 sequence")
}
为什么? 请告诉我。谢谢!
答案 0 :(得分:1)
struct Error: ErrorType {
}
func f() throws -> Void {
throw Error()
}
/*
try! f() // expression unexpectedly raised an error: Error()
*/
let a = try? f()
a == nil // true
do {
try f()
} catch {
print("ERROR")
}
// print "ERROR"
在您的情况下CryptoSwift.AES.Error.BlockSizeExceeded,结果为nil