如何移动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
}

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

至于您的查询

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
]

这将创建用于为指定的访问组创建键的查询。我想您可以自己计算更新查询。

最新更新