如何将SecKey从应用程序钥匙串移动到共享钥匙串组

问题描述

我正在iOS应用程序中生成私钥,以实现服务器与应用程序之间的安全通信。 私钥存储在钥匙串中。在新版本的应用中,由于通知扩展,我想使用共享钥匙串组。如何将存储在应用程序钥匙串中的私钥转移到共享组钥匙串。下面是我用来生成私钥的代码

func createPrivateKey(withLabel label: String) throws -> SecKey {
    let privateKeyAttrs: [String: Any] = [
        kSecAttrIsPermanent as String: true,kSecAttrApplicationLabel as String: label,kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,]

    let attributes: [String: Any] = [
        kSecAttrKeyType as String: kSecAttrKeyTypeRSA,kSecAttrKeySizeInBits as String: 2048,kSecPrivateKeyAttrs as String: privateKeyAttrs,]

    var error: Unmanaged<CFError>?
    guard let privateKey = SecKeyCreaterandomKey(attributes as CFDictionary,&error) else {
        // swiftlint:disable:next force_unwrapping
        throw error!.takeRetainedValue() as Error
    }
    return privateKey
}

解决方法

您必须在创建时指定访问组,或使用新的访问组更新现有密钥。完成此操作后,应正确设置权利,以便您创建的应用和扩展程序可以访问正确的钥匙串访问组。请仔细阅读,因为应用程序组和钥匙串共享组之间只有一线之隔。确保设置正确的(documentation here)。

关于您的查询

let accessGroup = "<# Your Team ID #>.com.example.SharedItems"
let attributes: [String: Any] = [
    kSecAttrKeyType as String: kSecAttrKeyTypeRSA,kSecAttrKeySizeInBits as String: 2048,kSecAttrAccessGroup as String: accessGroup,kSecPrivateKeyAttrs as String: privateKeyAttrs
]

这将创建查询,以为您指定的访问组创建密钥。我想您可以自己找出更新查询。