目的
為了能使用安全的http通道,避免路由劫持芝此,抓包等方法竊取重要數(shù)據(jù)骇两,為了實現(xiàn)蘋果ATS(App Transport Security)朝群,使用https(http通道加入SSL層)通道加密進(jìn)行接口設(shè)計,達(dá)到網(wǎng)絡(luò)數(shù)據(jù)安全的目的径缅。項目需求掺栅,加上蘋果無限期延遲ATS的要求,在未來芥驳,https必須會使用柿冲。
證書
在https雙向認(rèn)證的要求下,服務(wù)端需要簽發(fā)服務(wù)器證書和客戶端證書兆旬。iOS所需要的證書如下:
- 服務(wù)端.cer(server.cer)
- 客戶端.p12(client.p12)
使用AFNetworking 3.0
AFHTTPSessionManager
+ (AFHTTPSessionManager *)networkingManager
{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript",@"text/plain", nil];
manager.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
//啟動證書驗證
manager.securityPolicy = [self securityPolicy];
[manager setSessionDidBecomeInvalidBlock:^(NSURLSession * _Nonnull session, NSError * _Nonnull error) {
LPLog(@"%@",error.localizedDescription);
}];
//啟用雙向認(rèn)證需要下面的代碼假抄,如果只是單向認(rèn)證則不需要下面代碼,下面是開啟客戶端驗證的代碼丽猬。
__weak typeof(manager)weakSelf = manager;
[manager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession*session, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing*_credential) {
__strong typeof(manager) man = weakSelf;
NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
__autoreleasing NSURLCredential *credential =nil;
if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
if([man.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
if(credential) {
disposition =NSURLSessionAuthChallengeUseCredential;
} else {
disposition =NSURLSessionAuthChallengePerformDefaultHandling;
}
} else {
disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
}
} else {
// 客戶端驗證
SecIdentityRef identity = NULL;
SecTrustRef trust = NULL;
//客戶端證書路徑
NSString *p12 = [[NSBundle mainBundle] pathForResource:@"client" ofType:@"p12"];
NSFileManager *fileManager =[NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:p12]){ NSLog(@"client.p12:not exist"); }
else {
NSData *PKCS12Data = [NSData dataWithContentsOfFile:p12];
if ([self extractIdentity:&identity andTrust:&trust fromPKCS12Data:PKCS12Data]) {
SecCertificateRef certificate = NULL;
SecIdentityCopyCertificate(identity, &certificate);
const void*certs[] = {certificate};
CFArrayRef certArray =CFArrayCreate(kCFAllocatorDefault, certs,1,NULL);
credential =[NSURLCredential credentialWithIdentity:identity certificates:(__bridge NSArray*)certArray persistence:NSURLCredentialPersistencePermanent];
disposition = NSURLSessionAuthChallengeUseCredential;
CFRelease(certArray);
}
}
}
*_credential = credential;
return disposition;
}];
return manager;
}
啟用服務(wù)器證書驗證
+ (AFSecurityPolicy *)securityPolicy
{
//服務(wù)器證書的路徑宿饱,開啟服務(wù)器驗證
NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"server" ofType:@"cer"];
NSData *certData = [NSData dataWithContentsOfFile:cerPath];
// AFSSLPinningModeCertificate 使用證書驗證模式
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
//允許自建證書
securityPolicy.allowInvalidCertificates = YES;
//關(guān)閉域名驗證
securityPolicy.validatesDomainName = NO;
securityPolicy.pinnedCertificates = [NSSet setWithObjects:certData, nil];
return securityPolicy;
}
驗證客戶端證書
+(BOOL)extractIdentity:(SecIdentityRef*)outIdentity andTrust:(SecTrustRef *)outTrust fromPKCS12Data:(NSData *)inPKCS12Data {
OSStatus securityError = errSecSuccess;
//客戶端證書密碼
NSDictionary*optionsDictionary = [NSDictionary dictionaryWithObject:@"123456"
forKey:(__bridge id)kSecImportExportPassphrase];
CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
securityError = SecPKCS12Import((__bridge CFDataRef)inPKCS12Data,(__bridge CFDictionaryRef)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 {
return NO;
}
return YES;
}
問題
客戶端證書和服務(wù)器證書都必須由服務(wù)器生成,如果驗證失敗脚祟,很大可能就是證書生成錯誤的問題谬以。