SecKeyRef 始终为空,即使我没有从任何状态中得到任何错误。我最初认为这是一个弧线问题,但演员表看起来还不错。任何帮助,将不胜感激。
+ (SecKeyRef)addPublicKey:(NSString *)key withTag:(NSString *)tag
{
// This will be base64 encoded, decode it.
NSData *d_key = [key dataUsingEncoding:NSUTF8StringEncoding];
if (d_key == nil) return (FALSE);
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);
CFTypeRef persistKey = nil;
// Add persistent version of the key to system keychain
[publicKey setObject:d_key forKey:(__bridge id)kSecValueData];
[publicKey setObject:(__bridge id) kSecAttrKeyClassPublic forKey:(__bridge id)kSecAttrKeyClass];
[publicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnPersistentRef];
OSStatus secStatus = SecItemAdd((__bridge CFDictionaryRef)publicKey, &persistKey);
NSLog(@"OSStatus = %ld", secStatus); // Always returns no error = 0
if (persistKey != nil) CFRelease(persistKey);
if ((secStatus != noErr) && (secStatus != errSecDuplicateItem)) {
return nil;
}
// Now fetch the SecKeyRef version of the key
SecKeyRef keyRef;
[publicKey removeObjectForKey:(__bridge id)kSecValueData];
[publicKey removeObjectForKey:(__bridge id)kSecReturnPersistentRef];
[publicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnRef];
[publicKey setObject:(__bridge id)kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
secStatus = SecItemCopyMatching((__bridge CFDictionaryRef)publicKey, (CFTypeRef *)&keyRef);
NSLog(@"secStatus = %ld", secStatus); // Always returns no error = 0
return keyRef; // Always null!
}