经过大量的研究和尝试,我现在可以回答自己了。也希望它对你有用。
实际上,我需要的是使用 CFStream 实现客户端 SSL 身份验证。所以我需要做这些:
- 将 PKCS #12 文件放入我的应用程序包中
- 阅读此
NSData
文件pkcsData
- 使用方法
SecPKCS12Import
导入pkcsData
- 从上面导入的数据中获取身份和证书,并生成证书数组
- 将数组设置为键入您
kCFStreamSSLCertificates
的kCFStreamPropertySSLSettings
CFWriteStreamRef
下面的示例代码:
// Read .p12 file
NSString *path = [[NSBundle mainBundle] pathForResource:@"client" ofType:@"p12"];
NSData *pkcs12data = [[NSData alloc] initWithContentsOfFile:path];
// Import .p12 data
CFArrayRef keyref = NULL;
OSStatus sanityChesk = SecPKCS12Import((__bridge CFDataRef)pkcs12data,
(__bridge CFDictionaryRef)[NSDictionary
dictionaryWithObject:@"123456"
forKey:(__bridge id)kSecImportExportPassphrase],
&keyref);
if (sanityChesk != noErr) {
NSLog(@"Error while importing pkcs12 [%ld]", sanityChesk);
} else
NSLog(@"Success opening p12 certificate.");
// Identity
CFDictionaryRef identityDict = CFArrayGetValueAtIndex(keyref, 0);
SecIdentityRef identityRef = (SecIdentityRef)CFDictionaryGetValue(identityDict,
kSecImportItemIdentity);
// Cert
SecCertificateRef cert = NULL;
OSStatus status = SecIdentityCopyCertificate(identityRef, &cert);
if (status)
NSLog(@"SecIdentityCopyCertificate failed.");
// the certificates array, containing the identity then the root certificate
NSArray *myCerts = [[NSArray alloc] initWithObjects:(__bridge id)identityRef, (__bridge id)cert, nil];
//
[SSLOptions setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCFStreamSSLAllowsExpiredRoots];
[SSLOptions setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCFStreamSSLAllowsExpiredCertificates];
[SSLOptions setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCFStreamSSLAllowsAnyRoot];
[SSLOptions setObject:[NSNumber numberWithBool:NO] forKey:(NSString *)kCFStreamSSLValidatesCertificateChain];
[SSLOptions setObject:@"test.domain.com:443" forKey:(NSString *)kCFStreamSSLPeerName];
[SSLOptions setObject:(NSString *)kCFStreamSocketSecurityLevelNegotiatedSSL forKey:(NSString*)kCFStreamSSLLevel];
[SSLOptions setObject:(NSString *)kCFStreamSocketSecurityLevelNegotiatedSSL forKey:(NSString*)kCFStreamPropertySocketSecurityLevel];
[SSLOptions setObject:myCerts forKey:(NSString *)kCFStreamSSLCertificates];
[SSLOptions setObject:[NSNumber numberWithBool:NO] forKey:(NSString *)kCFStreamSSLIsServer];
[_outputStream setProperty:SSLOptions
forKey:(__bridge id)kCFStreamPropertySSLSettings];
因为我使用的是 SocketRocket,所以我在自己的 fork 中添加了这些代码:https ://github.com/nickcheng/SocketRocket