Adding private key into iOS Keychain

前端 未结 2 1515
轻奢々
轻奢々 2020-12-08 03:16

I am trying to add a private key into the iOS keychain. The certificate (public key) works fine but the private key refuses... I am totally confused why the following code d

相关标签:
2条回答
  • 2020-12-08 03:25

    The following code worked for me:

    NSMutableDictionary *query = [[NSMutableDictionary alloc] init]; 
    [query setObject:(id)kSecClassKey forKey:(id)kSecClass]; 
    [query setObject:(id)kSecAttrAccessibleWhenUnlocked forKey:(id)kSecAttrAccessible]; 
    [query setObject:[NSNumber numberWithBool:YES] forKey:(id)kSecReturnData];
    
    //adding access key 
    [query setObject:(id)key forKey:(id)kSecAttrApplicationTag];
    
    
    //removing item if it exists 
    SecItemDelete((CFDictionaryRef)query);
    
    //setting data (private key) 
    [query setObject:(id)data forKey:(id)kSecValueData];
    
    CFTypeRef persistKey; OSStatus status = SecItemAdd((CFDictionaryRef)query, &persistKey);
    
    if(status) {
        NSLog(@"Keychain error occured: %ld (statuscode)", status);
        return NO; 
    }
    
    0 讨论(0)
  • 2020-12-08 03:42

    Sorry but I'll never be able to debug your code. Apple provides some sample code (KeychainItemWrapper) which lets you save one string (I recall). Its a big help dealing with the key chain. There is a gist on the web that is a modified version of that class, but saves and restores a dictionary (archived as a data object, which is what the Apple code does to the string). This lets you save multiple items in one interface to the keychain. The gist is here Keychain for NSDictionary/data

    0 讨论(0)
提交回复
热议问题