HTTPS雙向認證(AFNetworking 3.0)

HttpsManager.h

+(AFHTTPSessionManager *)SignalSSL;
+(AFHTTPSessionManager *)DualSSL;

HttpsManager.m

//單向:客戶端驗證服務(wù)器的CA證書
+(AFHTTPSessionManager *)SignalSSL{
    AFHTTPSessionManager *_manager = [AFHTTPSessionManager manager];
    NSString *certFilePath = [[NSBundle mainBundle] pathForResource:@"CA" ofType:@"cer"];
    
    NSData *certData = [NSData dataWithContentsOfFile:certFilePath];
    NSSet *certSet = [NSSet setWithObject:certData];
    AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:certSet];
    policy.allowInvalidCertificates = YES;
    policy.validatesDomainName = YES;
    _manager.securityPolicy = policy;
    _manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    //設(shè)置POST的請求的header
    [_manager.requestSerializer setValue:@"value" forHTTPHeaderField:@"key"];
    
    return _manager;
}
//雙向:客戶端驗證服務(wù)器的CA證書身弊,服務(wù)器驗證客戶端的p12證書
+(AFHTTPSessionManager *)DualSSL{
    __weak AFHTTPSessionManager *_manager = [AFHTTPSessionManager manager];
    NSString *certFilePath = [[NSBundle mainBundle] pathForResource:@"cacert" ofType:@"cer"];
    NSData *certData = [NSData dataWithContentsOfFile:certFilePath];
    NSSet *certSet = [NSSet setWithObject:certData];
    AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:certSet];
    policy.allowInvalidCertificates = YES;
    policy.validatesDomainName = YES;
    _manager.securityPolicy = policy;
    
    _manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //設(shè)置POST的請求的header
    [_manager.requestSerializer setValue:@"value" forHTTPHeaderField:@"key"];
    
    //客戶端請求驗證 重寫 setSessionDidReceiveAuthenticationChallengeBlock 方法
    __weak typeof(self)weakSelf = self;
    [_manager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession*session, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing*_credential) {
        NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
        __autoreleasing NSURLCredential *credential =nil;
        
        if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
            if([_manager.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 *p12Str = [[NSBundle mainBundle] pathForResource:@"p12證書" ofType:@"p12"];;
            NSData *PKCS12Data = [NSData dataWithContentsOfFile:p12Str];
            if ([[weakSelf class] extractIdentity:&identity andTrust:&trust fromPKCS12Data:PKCS12Data]){
                SecCertificateRef caRef = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)PKCS12Data);
                
                SecIdentityCopyCertificate(identity, &caRef);
                
                const void*certs[] = {caRef};
                CFArrayRef certArray =CFArrayCreate(kCFAllocatorDefault, certs,1,NULL);
                credential =[NSURLCredential credentialWithIdentity:identity certificates:(__bridge  NSArray*)certArray persistence:NSURLCredentialPersistencePermanent];
                disposition =NSURLSessionAuthChallengeUseCredential;
                
            }
        }
        *_credential = credential;
        return disposition;
    }];
    
    return _manager;

}

#pragma ---mark daili
+(BOOL)extractIdentity:(SecIdentityRef*)outIdentity andTrust:(SecTrustRef *)outTrust fromPKCS12Data:(NSData *)inPKCS12Data {
    OSStatus securityError = errSecSuccess;
    //client certificate password
    NSDictionary*optionsDictionary = [NSDictionary dictionaryWithObject:@"p12Pwd"
                                                                 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 {
        NSLog(@"Failedwith error code %d",(int)securityError);
        return NO;
    }
    return YES;
}

ViewController.m

//單向認證
- (IBAction)signalSSLRequest:(id)sender {
    //訪問服務(wù)器的參數(shù)
    
    NSDictionary *parameter = [NSDictionary dictionaryWithObjectsAndKeys:
                         @"libai",@"username",nil];
    //請求地址
    NSString *url = @"https://xxx";
    [[HttpsManager SignalSSL] POST:url parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"errMessage = %@",dic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"錯誤Error: %@", error);
    }];
}
//雙向認證
- (IBAction)DualSSLRequest:(id)sender {
    NSDictionary *parameter = @{@"name":@"libai"};
    NSString *url = @"https://xxx";
    [[HttpsManager DualSSL] POST:url parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"errMessage = %@",dic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"錯誤Error: %@", error);
    }];
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市如叼,隨后出現(xiàn)的幾起案子皿哨,更是在濱河造成了極大的恐慌贝攒,老刑警劉巖菠镇,帶你破解...
    沈念sama閱讀 217,657評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件几睛,死亡現(xiàn)場離奇詭異邓深,居然都是意外死亡阶淘,警方通過查閱死者的電腦和手機衙吩,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評論 3 394
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來溪窒,“玉大人坤塞,你說我怎么就攤上這事〕喊觯” “怎么了尺锚?”我有些...
    開封第一講書人閱讀 164,057評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長惜浅。 經(jīng)常有香客問我瘫辩,道長,這世上最難降的妖魔是什么坛悉? 我笑而不...
    開封第一講書人閱讀 58,509評論 1 293
  • 正文 為了忘掉前任伐厌,我火速辦了婚禮,結(jié)果婚禮上裸影,老公的妹妹穿的比我還像新娘挣轨。我一直安慰自己,他們只是感情好轩猩,可當(dāng)我...
    茶點故事閱讀 67,562評論 6 392
  • 文/花漫 我一把揭開白布卷扮。 她就那樣靜靜地躺著,像睡著了一般均践。 火紅的嫁衣襯著肌膚如雪晤锹。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,443評論 1 302
  • 那天彤委,我揣著相機與錄音鞭铆,去河邊找鬼。 笑死焦影,一個胖子當(dāng)著我的面吹牛车遂,可吹牛的內(nèi)容都是我干的封断。 我是一名探鬼主播,決...
    沈念sama閱讀 40,251評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼舶担,長吁一口氣:“原來是場噩夢啊……” “哼坡疼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起衣陶,我...
    開封第一講書人閱讀 39,129評論 0 276
  • 序言:老撾萬榮一對情侶失蹤柄瑰,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后祖搓,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體狱意,經(jīng)...
    沈念sama閱讀 45,561評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡湖苞,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,779評論 3 335
  • 正文 我和宋清朗相戀三年拯欧,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片财骨。...
    茶點故事閱讀 39,902評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡镐作,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出隆箩,到底是詐尸還是另有隱情该贾,我是刑警寧澤,帶...
    沈念sama閱讀 35,621評論 5 345
  • 正文 年R本政府宣布捌臊,位于F島的核電站杨蛋,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏理澎。R本人自食惡果不足惜逞力,卻給世界環(huán)境...
    茶點故事閱讀 41,220評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望糠爬。 院中可真熱鬧寇荧,春花似錦、人聲如沸执隧。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,838評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽镀琉。三九已至峦嗤,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間屋摔,已是汗流浹背寻仗。 一陣腳步聲響...
    開封第一講書人閱讀 32,971評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留凡壤,地道東北人署尤。 一個月前我還...
    沈念sama閱讀 48,025評論 2 370
  • 正文 我出身青樓耙替,卻偏偏與公主長得像,于是被迫代替她去往敵國和親曹体。 傳聞我的和親對象是個殘疾皇子俗扇,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,843評論 2 354

推薦閱讀更多精彩內(nèi)容