【问题标题】:How can I save a NSString public key in the key chain and then get a SecKeyRef of it?如何将 NSString 公钥保存在密钥链中,然后获取它的 SecKeyRef?
【发布时间】:2012-02-18 12:33:07
【问题描述】:

我有一个NSString,它应该是一个公钥。我想将它存储在钥匙串中,然后获取它的SecKeyRef,以便在SecKeyEncrypt等其他与安全相关的功能中使用它。

为了存储我使用SecItemAdd,假设我还有一个公钥标识符。我试图得到一个持久的 ref,然后用这个得到一个 SecKeyRefSecItemCopyMatching。我使用以下两个功能。在将密钥字符串传递给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。有谁知道为什么?

【问题讨论】:

    标签: ios5 nsstring keychain


    【解决方案1】:

    查看 Apple 的 Crypto Exercise。为了将公钥添加到 KeyChain,有必要剥离附加到它的标头。 Apple 的示例就是这样做的,而且代码很容易重用。

    【讨论】:

      猜你喜欢
      • 2014-08-19
      • 2011-08-24
      • 2012-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-29
      相关资源
      最近更新 更多