即使我没有从任何状态中得到任何错误,SecKeyRef始终为null。最初我以为这是一个弧线问题,但是演员表看起来还不错。任何帮助,将不胜感激。
+ (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!
}
最佳答案
我正在做类似的事情,并且偶然发现了这篇文章。我尝试了您的代码,它对我来说效果很好,所以我认为它是正确的。我怀疑关键数据有误。我尝试通过这种方法提供错误的关键数据,它给了我像您所说的那样空引用。我正在使用模数和指数构建 public 密钥(ASN.1 DER),
https://github.com/meinside/iphonelib/blob/master/security/CryptoUtil.m#L67
请注意,有几个挂起的请求。
我认为也许您应该尝试使用.cer文件或使用openssl生成rsa密钥,并使用CryptoUtil使用模数和指数。