安全传输:从文件加载服务器证书

时间:2013-08-17 02:58:53

标签: c++ macos ssl keychain

我有一些C ++代码使用Apple Secure TransportKeychain API来创建SSL / TLS服务器(CLI)。 代码已经能够通过用户提供的指纹从现有的钥匙串加载服务器证书。

但是,出于兼容性原因,我想让服务器还从用户提供的文件集中加载证书+密钥(PEM)。

要明确:我不想将文件导入用户的钥匙串,而只是在“会话”中使用它。

基本上,请填写XXX:

bool AppleTLSContext::addCredentialFile(const std::string& certfile,
                                        const std::string& keyfile)
{
  if (tryAsFingerprint(certfile)) {
    return true;
  }

  // XXX
}

似乎可以使用SecItemImport和/或SecKeychainItemCreateFromContent将证书/密钥导入带有随机密码的丢弃钥匙串。

  • 没有使用丢弃的钥匙串是否有可行的方法?
  • 如果没有,“扔掉钥匙串”选项是否可行?
  • 另外,是否可以仅在内存中创建一次性钥匙串? (似乎SecKeychainCreate确实需要一条路径)

我正在寻找一个在编译后至少在OSX 10.6+上运行的解决方案(#ifdef可以)。

1 个答案:

答案 0 :(得分:1)

如果两个文件都可以进行分组并转换为pkcs 12格式,则可以使用SecPKCS12Import方法。

但是SecPKCS12Import在根上下文中无法正常工作。我不知道这种不端行为的原因。

OSStatus extractIdentityAndTrust(CFDataRef inPKCS12Data,
                             SecIdentityRef *outIdentity,
                             SecTrustRef *outTrust,
                             CFStringRef keyPassword)
{

OSStatus securityError = errSecSuccess;
const void *keys[] = { kSecImportExportPassphrase };
const void *values[] = { keyPassword };
CFDictionaryRef optionsDictionary = NULL;

optionsDictionary = CFDictionaryCreate(
                                       NULL, keys,
                                       values, (keyPassword ? 1 : 0),
                                       NULL, NULL);
CFArrayRef items = NULL;
securityError = SecPKCS12Import(inPKCS12Data,
                                optionsDictionary,
                                &items);

if (securityError == 0)
{ 
    CFDictionaryRef myIdentityAndTrust = (CFDictionaryRef)CFArrayGetValueAtIndex (items, 0);

    const void *tempIdentity = NULL;
    tempIdentity = CFDictionaryGetValue (myIdentityAndTrust,
                                         kSecImportItemIdentity);
    CFRetain(tempIdentity);
    *outIdentity = (SecIdentityRef)tempIdentity;
    const void *tempTrust = NULL;
    tempTrust = CFDictionaryGetValue (myIdentityAndTrust, kSecImportItemTrust);
    CFRetain(tempTrust);
    *outTrust = (SecTrustRef)tempTrust;
}
if (optionsDictionary) 
    CFRelease(optionsDictionary);
if (items)
    CFRelease(items);
return securityError;
}

阿南德