将客户端证书导入iPhone的钥匙串

4
我正在编写一个与服务器通信的应用程序,该服务器要求客户端使用客户端证书进行身份验证。我需要从应用程序包中提取.p12文件中的证书,并将其添加到应用程序钥匙串中。
我一直在尝试从苹果的"iOS证书、密钥和信任服务任务"中弄清楚如何使其工作,但对我来说似乎不完整,并且没有说明如何将任何内容添加到钥匙串中(?)。
我很迷茫,任何帮助都将不胜感激,谢谢!
1个回答

5

"iOS证书、密钥和信任服务任务"包含了从.p12文件中提取证书所需的足够信息。

  • 列表2-1演示了如何提取SecIdentityRef

  • 列表2-2第二行(// 1)展示了如何从SecIdentityRef复制SecCertificateRef

示例:加载p12文件,提取证书,安装到钥匙串。 (未包括错误处理和内存管理)

  NSString * password = @"Your-P12-File-Password";
  NSString * path = [[NSBundle mainBundle]
                     pathForResource:@"Your-P12-File" ofType:@"p12"];

  // prepare password
  CFStringRef cfPassword = CFStringCreateWithCString(NULL,
                                                     password.UTF8String,
                                                     kCFStringEncodingUTF8);
  const void *keys[]   = { kSecImportExportPassphrase };
  const void *values[] = { cfPassword };
  CFDictionaryRef optionsDictionary
  = CFDictionaryCreate(kCFAllocatorDefault, keys, values, 1,
                                                  NULL, NULL);

  // prepare p12 file content
  NSData * fileContent = [[NSData alloc] initWithContentsOfFile:path];
  CFDataRef cfDataOfFileContent = (__bridge CFDataRef)fileContent;

  // extract p12 file content into items (array)
  CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
  OSStatus status = errSecSuccess;
  status = SecPKCS12Import(cfDataOfFileContent,
                           optionsDictionary,
                           &items);
  // TODO: error handling on status

  // extract identity
  CFDictionaryRef yourIdentityAndTrust = CFArrayGetValueAtIndex(items, 0);
  const void *tempIdentity = NULL;
  tempIdentity = CFDictionaryGetValue(yourIdentityAndTrust,
                                      kSecImportItemIdentity);

  SecIdentityRef yourIdentity = (SecIdentityRef)tempIdentity;


  // get certificate from identity
  SecCertificateRef yourCertificate = NULL;
  status = SecIdentityCopyCertificate(yourIdentity, &yourCertificate);


  // at last, install certificate into keychain
  const void *keys2[]   = {    kSecValueRef,             kSecClass };
  const void *values2[] = { yourCertificate,  kSecClassCertificate };
  CFDictionaryRef dict
  = CFDictionaryCreate(kCFAllocatorDefault, keys2, values2,
                                            2, NULL, NULL);
  status = SecItemAdd(dict, NULL);

  // TODO: error handling on status

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接