从iOS导出SecKey到watchOS

我试图在我的iOS应用程序和它的watchOS等价物之间同步私人不对称密钥。 我已经尝试使用SecKeyCopyExternalRepresentation将其导出为CFData ,然后使用WatchConnectivity将其发送到手表。 但是,当它到达手表我无法将数据转换回SecKey 。 我尝试使用SecKeyCreateWithData尝试重新创build它,但它似乎只适用于对称密钥,因为当我尝试它,它使手表应用程序崩溃。 有任何想法吗?

iOS代码:

 func sendSharedKeyPair(keyPair: (publicKey: SecKey, privateKey: SecKey)) { var error: Unmanaged<CFError>? let publicKeyData = SecKeyCopyExternalRepresentation(keyPair.publicKey, &error) if let error = error { return print("Error sending shared key: \(error)") } let privateKeyData = SecKeyCopyExternalRepresentation(keyPair.privateKey, &error) if let error = error { return print("Error sending shared key: \(error)") } if let publicKeyData = publicKeyData, let privateKeyData = privateKeyData { session.sendMessage(["requestedCommand": WatchControllerCommands.sendSharedKeyPair.rawValue, "keyPair": ["publicKey": publicKeyData, "privateKey": privateKeyData]], replyHandler: nil, errorHandler: { error in print(error) }) } } 

watchOS代码:

 func session(_ session: WCSession, didReceiveMessage message: [String : Any]) { guard let requestedCommand = (message["requestedCommand"] as? String).flatMap({ WatchControllerCommands(rawValue: $0) }), requestedCommand == .sendSharedKeyPair else { return } guard let publicKeyData = (message["keyPair"] as? [String: Any])?["publicKey"].flatMap({ $0 as? Data }), let privateKeyData = (message["keyPair"] as? [String: Any])?["privateKey"].flatMap({ $0 as? Data }) else { return print("Couldn't parse keys") } let publicTag = "myAppTag" let privateTag = publicTag + ".private" let privateAttributes = [String(kSecAttrIsPermanent): true, String(kSecAttrApplicationTag): privateTag] as [String : Any] let publicAttributes = [String(kSecAttrIsPermanent): true, String(kSecAttrApplicationTag): publicTag] as [String : Any] var error: Unmanaged<CFError>? let publicCFData = publicKeyData as CFData let privateCFData = privateKeyData as CFData let publicCFDict = publicAttributes as CFDictionary let privateCFDict = privateAttributes as CFDictionary SecKeyCreateWithData(publicCFData, publicCFDict, &error) if let error = error { print(error) } SecKeyCreateWithData(privateCFData, privateCFDict, &error) if let error = error { print(error) } } 

从SecKeyCreateWithData周围的SecKeyCreateWithData

@param属性包含描述要导入的键的属性的字典。 这个字典中的键是来自SecItem.h的kSecAttr *常量。 强制属性是:* kSecAttrKeyType * kSecAttrKeyClass * kSecAttrKeySizeInBits

你的代码只定义了kSecAttrIsPermanentkSecAttrApplicationTag属性。