5

我正在尝试获取钥匙串项目的属性。此代码应查找所有可用属性,然后打印出它们的标签和内容。

根据文档,我应该看到像“cdat”这样的标签,但它们只是看起来像一个索引(即第一个标签是 0,下一个是 1)。这使它变得毫无用处,因为我无法分辨出哪个属性是我正在寻找的属性。

    SecItemClass itemClass;
    SecKeychainItemCopyAttributesAndData(itemRef, NULL, &itemClass, NULL, NULL, NULL);

    SecKeychainRef keychainRef;
    SecKeychainItemCopyKeychain(itemRef, &keychainRef);

    SecKeychainAttributeInfo *attrInfo;
    SecKeychainAttributeInfoForItemID(keychainRef, itemClass, &attrInfo);

    SecKeychainAttributeList *attributes;
    SecKeychainItemCopyAttributesAndData(itemRef, attrInfo, NULL, &attributes, 0, NULL);

    for (int i = 0; i < attributes->count; i ++)
    {
        SecKeychainAttribute attr = attributes->attr[i];
        NSLog(@"%08x %@", attr.tag, [NSData dataWithBytes:attr.data length:attr.length]);
    }

    SecKeychainFreeAttributeInfo(attrInfo);
    SecKeychainItemFreeAttributesAndData(attributes, NULL);
    CFRelease(itemRef);
    CFRelease(keychainRef);
4

2 回答 2

3

你应该在这里做两件事。首先,您需要在调用 SecKeychainAttributeInfoForItemID 之前处理“通用”itemClasses ...

switch (itemClass)
{
    case kSecInternetPasswordItemClass:
        itemClass = CSSM_DL_DB_RECORD_INTERNET_PASSWORD;
        break;
    case kSecGenericPasswordItemClass:
        itemClass = CSSM_DL_DB_RECORD_GENERIC_PASSWORD;
        break;
    case kSecAppleSharePasswordItemClass:
        itemClass = CSSM_DL_DB_RECORD_APPLESHARE_PASSWORD;
        break;
    default:
        // No action required
}

其次,您需要将 attr.tag 从 FourCharCode 转换为字符串,即

NSLog(@"%c%c%c%c %@",
    ((char *)&attr.tag)[3],
    ((char *)&attr.tag)[2],
    ((char *)&attr.tag)[1],
    ((char *)&attr.tag)[0],
    [[[NSString alloc]
        initWithData:[NSData dataWithBytes:attr.data length:attr.length]
        encoding:NSUTF8StringEncoding]
    autorelease]]);

请注意,我还将数据作为字符串输出——它几乎总是 UTF8 编码的数据。

于 2010-03-26T01:37:41.277 回答
1

我认为文档会导致一些混乱。

我看到的数字似乎是keys 的钥匙串项属性常量

但是,SecKeychainItemCopyAttributesAndData 返回一个 SecKeychainAttributeList 结构,其中包含一个 SecKeychainAttributes 数组。来自 TFD:

tag 一个 4 字节的属性标记。有关有效属性类型,请参阅“钥匙串项属性常量”。

属性常量(非“for keys”种类)是我希望看到的 4 字符值。

于 2009-07-27T04:57:34.033 回答