用Google搜索但无法找到有关如何在swift中为钥匙串设置此属性的任何内容。 使用Obj-C有一些零碎的东西,但试图找到Swift使用钥匙链和Obj-C之间的对应关系几乎是不可能的。
我已经有一些现有的代码(来自Realm Swift文档)来设置加密密钥,但是想要将访问权从默认设置为kSecAttrAccessibleAfterFirstUnlock。
class func getKey() -> NSData {
let keychainIdentifier = "Realm.EncryptionKey"
let keychainIdentifierData = keychainIdentifier.data(using: String.Encoding.utf8, allowLossyConversion: false)!
// First check in the keychain for an existing key
var query: [NSString: AnyObject] = [
kSecClass: kSecClassKey,
kSecAttrApplicationTag: keychainIdentifierData as AnyObject,
kSecAttrKeySizeInBits: 512 as AnyObject,
kSecReturnData: true as AnyObject
]
var dataTypeRef: AnyObject?
var status = withUnsafeMutablePointer(to: &dataTypeRef) { SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0)) }
if status == errSecSuccess {
return dataTypeRef as! NSData
}
// No pre-existing key from this application, so generate a new one
let keyData = NSMutableData(length: 64)!
let result = SecRandomCopyBytes(kSecRandomDefault, 64, keyData.mutableBytes.bindMemory(to: UInt8.self, capacity: 64))
assert(result == 0, "Failed to get random bytes")
// Store the key in the keychain
query = [
kSecClass: kSecClassKey,
kSecAttrApplicationTag: keychainIdentifierData as AnyObject,
kSecAttrKeySizeInBits: 512 as AnyObject,
kSecValueData: keyData
]
status = SecItemAdd(query as CFDictionary, nil)
return keyData
}
答案 0 :(得分:2)
将kSecAttrAccessible: kSecAttrAccessibleAfterFirstUnlock
添加到用于添加密钥的查询字典中。
如果要在已添加辅助功能后更新辅助功能状态,则需要在传递给kSecValueData
的字典中指定kSecAttrAccessible
和SecItemUpdate
个键。