Cocoa interface to MacOS X Keychain

2019-03-24 09:48发布

问题:

I've got a bit of Mac code that needs to store, access and update passwords in order to connect users with a web API. The right place to put this information should be the Mac Keychain, but there doesn't seem to be a cocoa interface (see this answer) -- is this still correct?

I've looked at Apple's Keychain documentation, and the API seems incredibly clunky. I can store to it and retrieve records, but anything more complex seems to require a lot of thought as to what might go wrong (see this list of error codes).

Is there a better interface to the Mac keychain, aside from slogging through the C code? The closest I've come is EMKeychain but it seems like it needs a bit of work (e.g. no error handling code aside from spitting to the console).

回答1:

You should take a look at SSKeychain. Works great, awesome code.



回答2:

Too late answer but would be good for future help. Below is what I did to save the password in Keychain of Mac

#pragma -mark Password save in Keychain

-(NSURLProtectionSpace *)createProtectionSpaceForBasicAuthentication{

    NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc]
                                             initWithHost:@"http://yourURLHere"
                                             port:1804  //add Your port here
                                             protocol:@"http" //can be pass as nil 
                                             realm:nil
                                             authenticationMethod:NSURLAuthenticationMethodHTTPBasic];
    return protectionSpace;
}

-(void )createCredentialForUsername:(NSString *)username Password:(NSString *)password{

    NSURLCredential *credentialObject;
    credentialObject = [NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistencePermanent];
    [[NSURLCredentialStorage sharedCredentialStorage] setCredential:credentialObject forProtectionSpace:[self createProtectionSpaceForBasicAuthentication]];
}

For saving password

- (IBAction)saveButtonClicked:(id)sender {
    [self createCredentialForUsername:@"User_Name" Password:@"Your_Pass"];
}

for fetching the password

NSURLCredential *credential;
NSDictionary *credentials;
credentials = [[NSURLCredentialStorage sharedCredentialStorage] credentialsForProtectionSpace:[self createProtectionSpaceForBasicAuthentication]];
credential = [credentials.objectEnumerator nextObject];
    NSLog(@"Username: %@ and password %@", credential.user, credential.password);

When we run the app to fetch password, we will get user action prompt for keychain access.



回答3:

Late to the party, as always, but I can recommend UICKeyChainStore.