简体   繁体   English

如何在Swift中将keychain的访问权限设置为kSecAttrAccessibleAfterFirstUnlock?

[英]How do you set the keychain's access to be kSecAttrAccessibleAfterFirstUnlock in Swift?

Googled but can't find anything on how to set this attribute for the keychain in swift. 谷歌搜索但无法找到有关如何在swift中为钥匙串设置此属性的任何内容。 There's a few bits and pieces about it with Obj-C, but trying to find a correspondence between Swift usage of the keychain and Obj-C is bloddy impossible almost. Obj-C有一些零碎的东西,但试图找到Swift使用钥匙链和Obj-C之间的对应关系几乎是不可能的。

I've got some existing code (from the Realm Swift documentation) to set an encryption key, but want to set the access from the default to kSecAttrAccessibleAfterFirstUnlock. 我有一些现有的代码(来自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
}

Add kSecAttrAccessible: kSecAttrAccessibleAfterFirstUnlock to the query dictionary you use to add the key. kSecAttrAccessible: kSecAttrAccessibleAfterFirstUnlock添加到用于添加密钥的查询字典中。

If you want to update the accessibility status after its already been added, you need to specify the kSecValueData and kSecAttrAccessible keys in the dictionary you pass to SecItemUpdate . 如果要在已添加辅助功能后更新辅助功能状态,则需要在传递给SecItemUpdate的字典中指定kSecValueDatakSecAttrAccessible密钥。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM