我有一个NSString
,它应该是公钥。我想将它存储在钥匙串中,然后获取SecKeyRef
,以便在SecKeyEncrypt
等其他安全相关功能中使用它。
对于存储,我使用SecItemAdd
假设我也有公钥的标识符。我尝试获得持久性参考,然后使用此SecKeyRef
获得SecItemCopyMatching
。我使用以下两个函数。在我将密钥串传递给putKey
之前,我将其转换为NSData
。
-(SecKeyRef)putKey:(NSData *)key withIdentifier:(NSString *)identifier
{
OSStatus status = noErr;
SecKeyRef keyRef = nil;
CFTypeRef persKey = nil;
NSData * identifierTag = [[NSData alloc] initWithBytes:(const void *)[identifier UTF8String] length:[identifier length]];
NSMutableDictionary *queryKey = [[NSMutableDictionary alloc] init];
[queryKey setObject:(__bridge id)kSecClassKey forKey:(__bridge id)kSecClass];
[queryKey setObject:(__bridge id)kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
[queryKey setObject:identifierTag forKey:(__bridge id)kSecAttrApplicationTag];
[queryKey setObject:key forKey:(__bridge id)kSecValueData];
[queryKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnPersistentRef];
status = SecItemAdd((__bridge CFDictionaryRef)queryKey, (CFTypeRef *)&persKey);
if (status == errSecDuplicateItem) NSLog(@"Key %@ already exists in the KeyStore, OSStatus = %ld.", identifier, status);
else if (status != noErr) NSLog(@"Error putting key %@ in KeyStore, OSStatus = %ld.", identifier, status);
keyRef = [self getKeyRefWithPersistentKeyRef:persKey];
return keyRef;
}
- (SecKeyRef)getKeyRefWithPersistentKeyRef:(CFTypeRef)persistentRef
{
OSStatus sanityCheck = noErr;
SecKeyRef keyRef = NULL;
if (persistentRef == NULL) NSLog(@"persistentRef object cannot be NULL.");
NSMutableDictionary * queryKey = [[NSMutableDictionary alloc] init];
// Set the SecKeyRef query dictionary.
[queryKey setObject:(__bridge id)persistentRef forKey:(__bridge id)kSecValuePersistentRef];
[queryKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnRef];
// Get the key reference.
sanityCheck = SecItemCopyMatching((__bridge CFDictionaryRef)queryKey, (CFTypeRef *)&keyRef);
return keyRef;
}
SecItemAdd
成功返回持久密钥ref。
SecItemCopyMatching
返回0x0。谁知道为什么?