osx macOS公钥导入到keychain重复

时间:2017-03-11 00:54:55

标签: swift macos keychain macos-sierra

我正在尝试将RSA公钥永久导入到钥匙串中

let params: [NSString: AnyObject] = [
    kSecClass: kSecClassKey,
    kSecAttrKeyType: kSecAttrKeyTypeRSA,
    kSecAttrApplicationTag: tag as AnyObject,
    kSecValueData: data as AnyObject,
    kSecReturnPersistentRef: true as AnyObject
]

let persistKey = UnsafeMutablePointer<AnyObject?>(mutating: nil)
let status = SecItemAdd(params as CFDictionary, persistKey)

...

不幸的是,密钥(无论哪个)获取errSecDuplicateItem但是如果我使用SecItemCopyMatching选择它...我得到errSecItemNotFound

我尝试了多种解决方案,例如添加帐户等不同的属性..但是大多数这些最终会导致未知的参数错误。

我确定密钥是正确的,因为SecKeyCreateWithData很好用。

修改 这是收集钥匙的方式:

        let params: [NSString: AnyObject] = [
            kSecClass: kSecClassKey,
            kSecAttrKeyType: kSecAttrKeyTypeRSA,
            kSecAttrApplicationTag: tag as AnyObject,
            kSecReturnRef: true as AnyObject
        ]

    var keyRef: AnyObject? = nil
    status = SecItemCopyMatching(params, &keyRef)

如果您在钥匙串应用程序中手动查找密钥,也无法找到该密钥

1 个答案:

答案 0 :(得分:0)

我有同样的问题。代码在iOS上运行正常,但我无法让它适用于macOS。 然后我使用Apple的文档https://developer.apple.com/documentation/security/certificate_key_and_trust_services/keys/storing_keys_as_data

重写了代码

因此,从SecKeyRef给出的公钥获取Data的代码就是:

let options: [String: Any] = [kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
                              kSecAttrKeyClass as String: kSecAttrKeyClassPublic,
                              kSecAttrKeySizeInBits as String : 2048]
var error: Unmanaged<CFError>?
guard let key = SecKeyCreateWithData(data as CFData,
                                     options as CFDictionary,
                                     &error) else {
                                        throw error!.takeRetainedValue() as Error
}