如何在密钥链中保存NSString公钥,然后获取它的SecKeyRef?

时间:2012-02-18 12:33:08

标签: ios5 nsstring keychain

我有一个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。谁知道为什么?

1 个答案:

答案 0 :(得分:0)

结帐Apple的Crypto Exercise。为了向KeyChain添加公钥,必须剥离附加到它的标头。 Apple的示例显示了这样做,代码很容易重用。