无法从钥匙串获取对称密钥



尝试从钥匙串创建并检索对称密钥:

添加密钥

let key  = Data(repeating: 0xee, count: 32)
let name = "test"
let attributes = [
kSecAttrKeyType: kSecAttrKeyTypeAES,
kSecAttrKeySizeInBits: NSNumber(value: 256)
] as CFDictionary
var error: Unmanaged<CFError>?
let secKey = SecKeyCreateFromData(attributes, key as CFData, &error)
let addquery = [
kSecClass: kSecClassKey,
kSecAttrKeyClass: kSecAttrKeyClassSymmetric,
kSecAttrLabel: name,
kSecValueRef: secKey!
] as CFDictionary
let status = SecItemAdd(addquery as CFDictionary, nil)
if status != errSecSuccess {
print(SecCopyErrorMessageString(status, nil)!)
}

钥匙串项目已创建

获取密钥

let name = "test"
let getquery = [
kSecClass: kSecClassKey,
kSecAttrKeyClass: kSecAttrKeyClassSymmetric,
kSecAttrLabel: name
] as [CFString : Any]
var secKey: CFTypeRef?
let status = SecItemCopyMatching(getquery as CFDictionary, &secKey)
if status == errSecSuccess {
if let dic = SecKeyCopyAttributes(secKey as! SecKey) as? [CFString: Any] {
if let key = dic[kSecValueData] {
print("Ok")
} else {
print("Cannot get the key")
}
} else {
print("Error retrieving dictionnary")
}
} else {
print(SecCopyErrorMessageString(status, nil)!)
}

如果在同一运行中添加并检索密钥,它将起作用。dic 中的元素数为 21。

但是,如果我只尝试获取存储在钥匙串中的密钥,我会获取字典而不是密钥。dic 中的元素数为 20(缺少 kSecValueData(。

获取密钥缺少哪些参数?

谢谢

为了从钥匙串中检索密钥,您还应该指定kSecAttrAccessible选项:

let attributes = [
kSecAttrKeyType: kSecAttrKeyTypeAES,
kSecAttrKeySizeInBits: NSNumber(value: 256),
kSecAttrAccessible: kSecAttrAccessibleWhenUnlocked
] as CFDictionary

当Mac解锁时,可以查询和检索这个。

然后,您可以使用已提供的代码

let getquery = [
kSecClass: kSecClassKey,
kSecAttrKeyClass: kSecAttrKeyClassSymmetric,
kSecAttrLabel: name,
kSecMatchLimit: kSecMatchLimitAll
] as [CFString : Any]
var secKeys: CFTypeRef?
let status = SecItemCopyMatching(getquery as CFDictionary, &secKeys)
if status == errSecSuccess {
for symmetricKey in (secKeys as! [SecKey]) {
guard let keyAttributes = SecKeyCopyAttributes(symmetricKey) as? [CFString: Any] else {
fatalError("No key attributes for symmetric key")
}

guard let keyData = keyAttributes[kSecValueData] as? Data else {
fatalError("No key data for symmetric key")
}
print("Key data retrieved: (keyData.base64EncodedString())")
}
}

现在,您可能会遇到已添加的旧键,这些键仍然不会返回任何数据(因为它们的可访问性标志设置不正确(。删除那些使用 Mac 上的"钥匙串访问"应用程序。之后,您应该能够添加 AES 密钥并检索 AES 密钥。

相关内容

  • 没有找到相关文章

最新更新