iOS SecItemAdd 返回-34018

Keywords: RSA encrypt, keychain , SecItemAdd, -34018

一、问题

升级了iOS 10和Xcode 8后RSA加密的时候调用SecItemAdd方法的时候总是得到 -34018。

代码如下:

    //a tag to read/write keychain storage
    NSString *tag = @"RSAUtil_PubKey";
    NSData *d_tag = [NSData dataWithBytes:[tag UTF8String] length:[tag length]];
    
    // Delete any old lingering key with the same tag
    NSMutableDictionary *publicKey = [[NSMutableDictionary alloc] init];
    [publicKey setObject:(__bridge id) kSecClassKey forKey:(__bridge id)kSecClass];
    [publicKey setObject:(__bridge id) kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
    [publicKey setObject:d_tag forKey:(__bridge id)kSecAttrApplicationTag];
    SecItemDelete((__bridge CFDictionaryRef)publicKey);
    
    // Add persistent version of the key to system keychain
    [publicKey setObject:data forKey:(__bridge id)kSecValueData];
    [publicKey setObject:(__bridge id) kSecAttrKeyClassPublic forKey:(__bridge id)
     kSecAttrKeyClass];
    [publicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)
     kSecReturnPersistentRef];
    
    CFTypeRef persistKey = nil;
    OSStatus status = SecItemAdd((__bridge CFDictionaryRef)publicKey, &persistKey);
    if (persistKey != nil){
        CFRelease(persistKey);
    }

执行到OSStatus status = SecItemAdd((__bridge CFDictionaryRef)publicKey, &persistKey);时,status = -34018,而正常情况下status = 0。

显然是publicKey没有成功的添加到KeyChain中。

二、解决方案
1.打开KeyChain Sharing

iOS SecItemAdd 返回-34018_第1张图片
keychain.png

你可能感兴趣的:(iOS SecItemAdd 返回-34018)