Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying iOS Keychain using Swift

I'm stuck converting the Keychain query result using Swift.

My request seems to be working:

let queryAttributes = NSDictionary(objects: [kSecClassGenericPassword, "MyService",     "MyAccount",       true],
                                   forKeys: [kSecClass,                kSecAttrService, kSecAttrAccount, kSecReturnData])


dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
    var dataTypeRef : Unmanaged<AnyObject>?
    let status = SecItemCopyMatching(queryAttributes, &dataTypeRef);

    let retrievedData : NSData = dataTypeRef!.takeRetainedValue() as NSData
    *** ^^^^can't compile this line^^^^
})

My problem is, code won't compile:

Bitcast requires both operands to be pointer or neither
  %114 = bitcast %objc_object* %113 to %PSs9AnyObject_, !dbg !487
Bitcast requires both operands to be pointer or neither
  %115 = bitcast %PSs9AnyObject_ %114 to i8*, !dbg !487
LLVM ERROR: Broken function found, compilation aborted!

I don't know how to convert Unmanaged<AnyObject> to NSData.

Any ideas?

like image 405
Damien Avatar asked Jun 10 '14 16:06

Damien


People also ask

How do I access Swift keychain?

To query the keychain and retrieve the items, we use the SecItemCopyMatching function. The two parameters it takes are actually the same ones as SecItemAdd . The way these two functions is the same: You specify a query, and get something in return, including nil. it returns a OSStatus like SecItemAdd .

How do I access keychain iOS?

Open the Settings app and tap your Apple ID banner at the top of the Settings menu. Tap iCloud. Scroll down the list and select Keychain.

What is the difference between keychain and Userdefaults?

A keychain is an encrypted container that holds passwords for multiple applications and secure services. Apple Inc. uses keychains as password management system in Mac OS and iOS. NSUserDefaults Provides a way for application behavior customization based on user preferences.

Is iOS keychain encrypted?

Overview. Keychain items are encrypted using two different AES-256-GCM keys: a table key (metadata) and a per-row key (secret key). Keychain metadata (all attributes other than kSecValue) is encrypted with the metadata key to speed searches, and the secret value (kSecValueData) is encrypted with the secret key.


1 Answers

Use withUnsafeMutablePointer function and UnsafeMutablePointer struct to retrieving the data, such as the following:

var result: AnyObject?
var status = withUnsafeMutablePointer(&result) { SecItemCopyMatching(queryAttributes, UnsafeMutablePointer($0)) }

if status == errSecSuccess {
    if let data = result as NSData? {
        if let string = NSString(data: data, encoding: NSUTF8StringEncoding) {
            // ...
        }
    }
}

it works fine with release (Fastest [-O]) build.

like image 144
kishikawa katsumi Avatar answered Oct 08 '22 07:10

kishikawa katsumi