将对称的SecKeyRef保存到OSX钥匙串

时间:2013-07-09 19:59:41

标签: cocoa keychain

我正在尝试使用OSX中的安全性转换创建对称加密密钥,然后将该密钥保存到钥匙串中。我能够创建一个工作密钥并将其保存到钥匙串,但是当我回想起密钥并尝试使用它时,我得到一个CDSA错误“检测到缺失值”。

也是相关的。在我将密钥保存到钥匙串后,如果我尝试手动删除它,我会收到一条错误消息“检测到缺失值”,如果我尝试创建另一个带有不同标签的密钥,我会被告知密钥已经存在于密钥链中。

这是我用来将SecKeyRef保存到钥匙串的代码,从一个安全转换示例拼凑而成。欢迎任何有关我可能做错的建议。是否还有我缺少的SecKeychainAttributeList的其他必需属性?我是否错误地存储了密钥数据本身?我不太熟悉在C工作。

+ (BOOL)addKey:(SecKeyRef)key withLabel:(NSString*)label
{
    OSStatus err;
    SecKeychainItemRef item = nil;

   const char *itemLabelUTF8 = [label UTF8String];

    SecKeychainAttribute attrs[] = {
        { kSecLabelItemAttr, strlen(itemLabelUTF8), (char *)itemLabelUTF8 }
    };

    SecKeychainAttributeList attributes = { sizeof(attrs) / sizeof(attrs[0]),
        attrs };

    err = SecKeychainItemCreateFromContent(
                                       kSecSymmetricKeyItemClass,//class of item being     created
                                       &attributes,//attributes dictionary
                                       sizeof(key),//length of buffer holding data to store
                                       key, //buffer with data to store
                                       NULL, // use the default keychain
                                       NULL,//access object to define access. null = access for this app
                                       &item);//reference to created item on return

    if (item) CFRelease(item);

    if (err == errSecSuccess) {
        DDLogVerbose(@"created keychain item");
        return YES;
    } else if (err == errSecDuplicateItem){
        DDLogVerbose(@"key already exists in keychain");
        return NO;
    } else {
        DDLogVerbose(@"error: %d", err);
        return NO;
    }
}

1 个答案:

答案 0 :(得分:0)

面对同样的问题。
但通常你应该使用SecItemAdd,这就是Apple DevDocs所说的:Apple DevDocs Keychain Service Tasks for OSX (at the end of the page)

我用以下代码存储对称密钥,实际上可行,但删除仍然是一团糟。 ;-) 任何建议也欢迎我。 希望它有所帮助:

// Identifier for symmetric key
static const uint8_t keyIdentfier[] = "this.is.my.TestKeyLabel";
NSData *tag = [[NSData alloc] initWithBytes:keyIdentfier length:sizeof(keyIdentfier)];

// Simple keygen algo - JUST FOR EXAMPLE DO NOT USE!
NSMutableData *key = [NSMutableData dataWithLength:8];
SecRandomCopyBytes(kSecRandomDefault, 8, key.mutableBytes);
NSString *base64key = [key base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:(__bridge id)kSecClassKey forKey:(__bridge id)kSecClass];
[dict setObject:tag forKey:(__bridge id)kSecAttrApplicationTag];
[dict setObject:(__bridge id)kSecAttrKeyClassSymmetric forKey:(__bridge id)kSecAttrKeyType];
[dict setObject:key forKey:(__bridge id)kSecValueData];

// Insert key into keychain based on dictionary attributes above
OSStatus osstatus = SecItemAdd((__bridge CFDictionaryRef)dict, NULL);