六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 184|回复: 0

使用服务器信任证书,访问https服务器

[复制链接]

升级  34%

3

主题

3

主题

3

主题

童生

Rank: 1

积分
17
 楼主| 发表于 2013-2-7 19:45:17 | 显示全部楼层 |阅读模式
参考ASIHHPRequest开源项目中的ClientCertificateTests.m源码。
链接:https://github.com/pokeb/asi-http-request/blob/master/Classes/Tests/ClientCertificateTests.m
以及:http://developer.apple.com/library/mac/#documentation/Security/Conceptual/CertKeyTrustProgGuide/iPhone_Tasks/iPhone_Tasks.html

+ (void)testClientCertificate {NSURL *httpsUrl = [NSURL URLWithString:@"https://xxxxxx.xx.xx"];ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:httpsUrl];SecIdentityRef identity = NULL;SecTrustRef trust = NULL;                //绑定证书,证书放在Resources文件夹中NSData *PKCS12Data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"client" ofType:@"p12"]];[HttpsTestViewController extractIdentity:&identity andTrust:&trust fromPKCS12Data:PKCS12Data];request = [ASIHTTPRequest requestWithURL:httpsUrl];[request setClientCertificateIdentity:identity];[request setValidatesSecureCertificate:NO];[request startSynchronous];error = [request error];if (!error) {NSString *response = [request responseString];NSLog(@"response is : %@",response);} else {NSLog(@"Failed to save to data store: %@", [error localizedDescription]);NSLog(@"%@",[error userInfo]);}}+ (BOOL)extractIdentity:(SecIdentityRef *)outIdentity andTrust:(SecTrustRef*)outTrust fromPKCS12Data:(NSData *)inPKCS12Data {OSStatus securityError = errSecSuccess;CFStringRef password = CFSTR("xxxxxx"); //证书密码const void *keys[] =   { kSecImportExportPassphrase };        const void *values[] = { password };CFDictionaryRef optionsDictionary = CFDictionaryCreate(NULL, keys,values, 1,NULL, NULL); CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);//securityError = SecPKCS12Import((CFDataRef)inPKCS12Data,(CFDictionaryRef)optionsDictionary,&items);securityError = SecPKCS12Import((CFDataRef)inPKCS12Data,optionsDictionary,&items); if (securityError == 0) { CFDictionaryRef myIdentityAndTrust = CFArrayGetValueAtIndex (items, 0);const void *tempIdentity = NULL;tempIdentity = CFDictionaryGetValue (myIdentityAndTrust, kSecImportItemIdentity);*outIdentity = (SecIdentityRef)tempIdentity;const void *tempTrust = NULL;tempTrust = CFDictionaryGetValue (myIdentityAndTrust, kSecImportItemTrust);*outTrust = (SecTrustRef)tempTrust;} else {NSLog(@"Failed with error code %d",(int)securityError);return NO;}return YES;}
项目中,要添加Security.framework。
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表