Apple的documentation for OS X谈到使用SecItemImport
获取SecKeyRef
。函数签名如下所示:
OSStatus SecItemImport (
CFDataRef importedData,
CFStringRef fileNameOrExtension,
SecExternalFormat *inputFormat,
SecExternalItemType *itemType,
SecItemImportExportFlags flags,
const SecItemImportExportKeyParameters *keyParams,
SecKeychainRef importKeychain,
CFArrayRef *outItems
);
以下代码将尝试加载包含单个RSA密钥的PKCS12字节数组:
#include <Security/Security.h>
#include <Security/SecKey.h>
#include <CoreFoundation/CoreFoundation.h>
int main(void) {
CFArrayRef array = NULL;
SecItemImportExportKeyParameters params;
SecExternalItemType itemType = kSecItemTypeUnknown;
SecExternalFormat format = kSecFormatUnknown;
params.flags = kSecKeyNoAccessControl;
UInt8 bytes[] = {
0x30, 0x82, 0x2, 0x1e, 0x2, 0x1, 0x3, 0x30, 0x82, 0x1, 0xe8, 0x6, 0x9, 0x2a, 0x86, 0x48, 0x86, 0xf7,
0xd, 0x1, 0x7, 0x1, 0xa0, 0x82, 0x1, 0xd9, 0x4, 0x82, 0x1, 0xd5, 0x30, 0x82, 0x1, 0xd1, 0x30, 0x82,
0x1, 0xcd, 0x6, 0x9, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0xd, 0x1, 0x7, 0x1, 0xa0, 0x82, 0x1, 0xbe, 0x4,
0x82, 0x1, 0xba, 0x30, 0x82, 0x1, 0xb6, 0x30, 0x82, 0x1, 0xb2, 0x6, 0xb, 0x2a, 0x86, 0x48, 0x86,
0xf7, 0xd, 0x1, 0xc, 0xa, 0x1, 0x2, 0xa0, 0x82, 0x1, 0x86, 0x30, 0x82, 0x1, 0x82, 0x30, 0x1c, 0x6,
0xa, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0xd, 0x1, 0xc, 0x1, 0x3, 0x30, 0xe, 0x4, 0x8, 0x8f, 0x14, 0x15,
0x85, 0x8e, 0x1c, 0x64, 0x6c, 0x2, 0x2, 0x8, 0x0, 0x4, 0x82, 0x1, 0x60, 0x86, 0x44, 0x55, 0x7e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, 0x0, 0x65, 0x30, 0x2d,
0x30, 0x21, 0x30, 0x9, 0x6, 0x5, 0x2b, 0xe, 0x3, 0x2, 0x1a, 0x5, 0x0, 0x4, 0x14, 0x95, 0x9, 0x91,
0xf7, 0x6c, 0x7f, 0x35, 0x99, 0x64, 0xfc, 0x3e, 0x5e, 0xcf, 0xb6, 0x24, 0x8a, 0xc, 0x54, 0x44, 0xc6,
0x4, 0x8, 0xfe, 0xe0, 0xe7, 0xbb, 0x72, 0xe1, 0xc9, 0x97
};
FILE* file = fopen( "test.p12", "wb" );
fwrite( bytes, sizeof(UInt8), sizeof(bytes)/sizeof(UInt8), file );
params.passphrase = CFStringCreateWithCString(kCFAllocatorDefault, "pass", kCFStringEncodingASCII);
CFDataRef dataref = CFDataCreate(kCFAllocatorDefault, bytes, sizeof(bytes)/sizeof(bytes[0]));
OSStatus res = SecItemImport(dataref, CFSTR(".p12"), &format, &itemType, 0, ¶ms, NULL, &array);
printf("response: %d\n", res);
printf("format: %d\n", format);
printf("itemType: %d\n", itemType);
printf("count: %ld\n", CFArrayGetCount(array));
}
要编译上述内容,您可以使用clang filename.c -framework Security -framework CoreFoundation
。
此代码不返回任何错误(OSStatus 0),但无法使用已解析的SecKeyRef
填充数组。我已经尝试了很多不同的标志但是无法让它返回所需的数据。有谁知道我做错了什么?
答案 0 :(得分:4)
这看起来像是一个Keychain错误。这并不令人震惊;钥匙串有很多小角落案件没有得到很好的处理。我打开雷达(bugreport.apple.com)。一些补充说明:
PKCS12通常用于存储证书和私钥。您只是导入一个裸私钥。我打赌它没有经过充分测试,尽管它声称得到了支持:
注意:导入PKCS12 blob时,通常会在outItems中返回一个SecIdentityRef对象和零个或多个其他SecCertificateRef对象。除非在没有匹配证书的传入blob中找到密钥,否则不会返回SecKeyRef对象。
如果有涉及证书的话,我会很好奇。
我已尝试使用钥匙串(使用SecKeychainCreate
创建)此代码。生成的钥匙串可由Keychain Access读取并包含私钥,因此导入正在运行。
我尝试使用与SecPKCS12Import相同的所有代码,但它返回相同的结果。例如,我确保memset()
参数结构,您的代码应该是,但不是。
作为一个无关紧要的点,你正在泄露密码。你应该在这里使用CFSTR()
来传递常量字符串。