簡體   English   中英

如何在Swift中將keychain的訪問權限設置為kSecAttrAccessibleAfterFirstUnlock?

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

谷歌搜索但無法找到有關如何在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
}

kSecAttrAccessible: kSecAttrAccessibleAfterFirstUnlock添加到用於添加密鑰的查詢字典中。

如果要在已添加輔助功能后更新輔助功能狀態,則需要在傳遞給SecItemUpdate的字典中指定kSecValueDatakSecAttrAccessible密鑰。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM