将SecKey从iOS导出到watchOS

时间:2017-04-26 14:45:45

标签: ios security watch-os

我正在尝试在我的iOS应用和其watchOS等效版之间同步私有非对称密钥。我尝试使用SecKeyCopyExternalRepresentation将其导出为CFData,然后使用WatchConnectivity将其发送到观看。但是当它进入手表时我无法将数据转换回SecKey。我尝试使用SecKeyCreateWithData尝试重新创建它,但似乎只适用于对称密钥,因为当我尝试它时,它会使手表应用程序崩溃。有什么想法吗?

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)
    }
}

1 个答案:

答案 0 :(得分:1)

来自SecKeyCreateWithData周围的headerdoc:

  

@param attributes包含描述键的属性的Dictionary   进口。这本词典中的键是kSecAttr *常量   来自SecItem.h。强制属性为:* kSecAttrKeyType *   kSecAttrKeyClass * kSecAttrKeySizeInBits

您的代码仅定义kSecAttrIsPermanentkSecAttrApplicationTag属性。