【发布时间】:2012-02-18 12:33:07
【问题描述】:
我有一个NSString,它应该是一个公钥。我想将它存储在钥匙串中,然后获取它的SecKeyRef,以便在SecKeyEncrypt等其他与安全相关的功能中使用它。
为了存储我使用SecItemAdd,假设我还有一个公钥标识符。我试图得到一个持久的 ref,然后用这个得到一个 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 成功返回一个持久密钥引用。
SecItemCopyMatching 返回 0x0。有谁知道为什么?
【问题讨论】: