How to use Keychain for saving password like GenericKeychain sample code

后端 未结 1 1714
抹茶落季
抹茶落季 2020-11-30 05:33

I want to save user\'s id and password in App.

What is recommendable encryption way when I save id and password.

I\'m finding more safe way from Jailbreak or

相关标签:
1条回答
  • 2020-11-30 05:57

    You can use the Security framework

    #import <Security/Security.h>

    To save a username and password for a server:

    -(void) saveUsername:(NSString*)user withPassword:(NSString*)pass forServer:(NSString*)server {
    
        // Create dictionary of search parameters
        NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:(__bridge id)(kSecClassInternetPassword),  kSecClass, server, kSecAttrServer, kCFBooleanTrue, kSecReturnAttributes, nil];
    
        // Remove any old values from the keychain
        OSStatus err = SecItemDelete((__bridge CFDictionaryRef) dict);
    
        // Create dictionary of parameters to add
        NSData* passwordData = [pass dataUsingEncoding:NSUTF8StringEncoding];
        dict = [NSDictionary dictionaryWithObjectsAndKeys:(__bridge id)(kSecClassInternetPassword), kSecClass, server, kSecAttrServer, passwordData, kSecValueData, user, kSecAttrAccount, nil];
    
        // Try to save to keychain
        err = SecItemAdd((__bridge CFDictionaryRef) dict, NULL);
    
    }
    

    To remove:

    -(void) removeAllCredentialsForServer:(NSString*)server {
    
        // Create dictionary of search parameters
        NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:(__bridge id)(kSecClassInternetPassword),  kSecClass, server, kSecAttrServer, kCFBooleanTrue, kSecReturnAttributes, kCFBooleanTrue, kSecReturnData, nil];
    
        // Remove any old values from the keychain
        OSStatus err = SecItemDelete((__bridge CFDictionaryRef) dict);
    
    }
    

    To read:

    -(void) getCredentialsForServer:(NSString*)server {
    
        // Create dictionary of search parameters
        NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:(__bridge id)(kSecClassInternetPassword),  kSecClass, server, kSecAttrServer, kCFBooleanTrue, kSecReturnAttributes, kCFBooleanTrue, kSecReturnData, nil];
    
        // Look up server in the keychain
        NSDictionary* found = nil;
        CFDictionaryRef foundCF;
        OSStatus err = SecItemCopyMatching((__bridge CFDictionaryRef) dict, (CFTypeRef*)&foundCF);
    
        // Check if found
        found = (__bridge NSDictionary*)(foundCF);
        if (!found) 
            return;
    
        // Found
        NSString* user = (NSString*) [found objectForKey:(__bridge id)(kSecAttrAccount)];
        NSString* pass = [[NSString alloc] initWithData:[found objectForKey:(__bridge id)(kSecValueData)] encoding:NSUTF8StringEncoding];
    
    }
    
    0 讨论(0)
提交回复
热议问题