`
sparrow82
  • 浏览: 40667 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

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

阅读更多
参考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。
分享到:
评论
2 楼 bewithme 2014-01-03  
为啥不要输入密钥库密码?
1 楼 bewithme 2014-01-03  
你好,为啥报

NSLocalizedDescription = "A connection failure occurred";
    NSUnderlyingError = "Error Domain=NSOSStatusErrorDomain Code=-9825 \"The operation couldn\U2019t be completed. (OSStatus error -9825.)

相关推荐

Global site tag (gtag.js) - Google Analytics