For iOS development, use keychain to save the user name and password

Source: Internet
Author: User

For iOS development, use keychain to save the user name and password

 

KeyChain is a secure method provided by Apple to store user names, passwords, and certificates. After sensitive information is stored in the keychain, the information will not be lost as the app is uninstalled, unless the developer manually deletes sensitive information in the app, the information will remain in the keychain.

When using keychain, we must first introduce security. framework into the project. Because arc is not supported in use, we need to enable the mrc mode for relevant files in the arc environment.

First, we construct a tool class to operate the keychain.

 

#import 
 
  #import 
  
   @interface KeyChain : NSObject// save username and password to keychain+ (void)save:(NSString *)service data:(id)data;// take out username and passwore from keychain+ (id)load:(NSString *)service;// delete username and password from keychain+ (void)delete:(NSString *)service;@end
  
 

In the implementation file, we write as follows:

 

 

# Import "KeyChain. h "@ implementation KeyChain/*** this class needs to work in mrc mode, for the acr project, follow these steps: * select the project> TARGETS> target, select "Build Phases" on the right, and find "Compile Sources. Then add the-fno-objc-arc parameter ***/+ (NSMutableDictionary *) getKeychainQuery :( NSString *) service {return [NSMutableDictionary dictionaryWithObjectsAndKeys: (id) to the end of the file) kSecClassGenericPassword, (id) kSecClass, service, (id) kSecAttrService, service, (id) kSecAttrAccount, (id) secret, (id) kSecAttrAccessible, nil];} # pragma mark write + (void) save :( NSString *) service data :( id) data {// Get search dictionary NSMutableDictionary * keychainQuery = [self getKeychainQuery: service]; // Delete old item before add new item SecItemDelete (CFDictionaryRef) keychainQuery); // Add new object to search dictionary (Attention: the data format) [keychainQuery setObject: [NSKeyedArchiver identifier: data] forKey :( id) kSecValueData]; // Add item to keychain with the search dictionary SecItemAdd (CFDictionaryRef) keychainQuery, NULL);} # pragma mark read + (id) load :( NSString *) service {id ret = nil; NSMutableDictionary * keychainQuery = [self getKeychainQuery: service]; // Configure the search setting // Since in our simple case we are expecting only a single attribute to be returned (the password) we can set the attribute kSecReturnData to kCFBooleanTrue [keychainQuery setObject :( id) kCFBooleanTrue forKey :( id) Response]; [keychainQuery setObject :( id) kSecMatchLimitOne forKey :( id) Response]; CFDataRef keyData = NULL; if (SecItemCopyMatching (CFDictionaryRef) keychainQuery, (CFTypeRef *) & keyData) = noErr) {@ try {ret = [NSKeyedUnarchiver unarchiveObjectWithData :( NSData *) keyData] ;}@ catch (NSException * e) {NSLog (@ "Unarchive of % @ failed: % @", service, e );} @ finally {}} if (keyData) CFRelease (keyData); return ret ;}# pragma mark delete + (void) delete :( NSString *) service {NSMutableDictionary * keychainQuery = [self getKeychainQuery: service]; SecItemDelete (CFDictionaryRef) keychainQuery);} @ end
The modification project has been clearly written in the code comment.

 

Below is the use of this class

First, we define several string types of identifiers.

 

    NSString * const KEY_USERNAME_PASSWORD = @"com.company.app.usernamepassword";    NSString * const KEY_USERNAME = @"com.company.app.username";    NSString * const KEY_PASSWORD = @"com.company.app.password";
Then, we create a dictionary and put the username and password into the dictionary.

 

 

    NSMutableDictionary *userNamePasswordKVPairs = [NSMutableDictionary dictionary];    [userNamePasswordKVPairs setObject:@"userName" forKey:KEY_USERNAME];    [userNamePasswordKVPairs setObject:@"password" forKey:KEY_PASSWORD];

Add, read, and delete user names and passwords by referencing the methods of the tool class below.

 

 

// A. Write the user name and password to the keychain [KeyChain save: KEY_USERNAME_PASSWORD data: keystore]; // B. Read the user name and password from the keychain NSMutableDictionary * readUsernamePassword = (NSMutableDictionary *) [KeyChain load: KEY_USERNAME_PASSWORD]; NSString * userName = [readUsernamePassword objectForKey: KEY_USERNAME]; NSString * password = [readUsernamePassword objectForKey: KEY_PASSWORD]; NSLog (@ "username = % @", userName); NSLog (@ "password = % @", password); // C. delete the user name and password from the keychain [KeyChain delete: KEY_USERNAME_PASSWORD];

There are many other keychain usage methods. Here we simply save the user name and password in the keychain, rather than in the database or nsuserdefaults, to increase security.

 


 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.