AFNetworking 3.0與服務端 自簽名證書 https雙向認證

原創文章遷移至
https://blog.ixianshang.net/2019/08/08/AFNetworking%203.0%E4%B8%8E%E6%9C%8D%E5%8A%A1%E7%AB%AF%20%E8%87%AA%E7%AD%BE%E5%90%8D%E8%AF%81%E4%B9%A6%20https%E5%8F%8C%E5%90%91%E8%AE%A4%E8%AF%81/index.html

iOS網絡安全現在越來越重要,一個抓包工具(charles等)隨隨便便就能抓到你所請求的數據,這些數據如果是明碼的后果很嚴重,不是指明文,可以通過這些數據來判定服務端部署的數據接口,更能夠嗅探到服務端的漏洞。

所以最近因公司業務及數據安全上的需要準備使用https方式進行數據請求。而且蘋果現在默認是https方式請求。

Apple CSR CER P12 mobileprovition 到底是什么

  • CSR(Certificate Signing Request)鑰匙串文件 為生成證書做基礎,要生成CER證書必須要有CSR私鑰,此私鑰包含了用戶自己的一些信息。這個文件是保存在我們的mac的(keychain)里面的, 此文件包含了(公鑰和私鑰)
  • CER 包含了開發者信息和公鑰
  • P12 它不僅包含CER的信息,還有私鑰信息,即: P12備份文件 = CER文件 + 私鑰;所以有了這個p12就再也不用擔心證書丟失了
  • mobileprovition 包含了上述所有內容 Certificate && App ID && Device, 這個Provisioning Profile文件會在打包時嵌入到.ipa的包里。本人理解的是 可以真機調試的憑證。

https原理

HTTPS(全稱:Hyper Text Transfer Protocol over Secure Socket Layer),是以安全為目標的HTTP通道,簡單講是HTTP的安全版。即HTTP下加入SSL層,HTTPS的安全基礎是SSL,因此加密的詳細內容就需要SSL。 它是一個URI scheme(抽象標識符體系),句法類同http:體系。用于安全的HTTP數據傳輸。https:URL表明它使用了HTTP,但HTTPS存在不同于HTTP的默認端口及一個加密/身份驗證層(在HTTP與TCP之間)。這個系統的最初研發由網景公司(Netscape)進行,并內置于其瀏覽器Netscape Navigator中,提供了身份驗證與加密通訊方法。(摘自百度百科)

PKI(公鑰基礎設施)技術是HTTPS的基礎,PKI與非對稱密鑰加密技術密切相關,包括消息摘要、數字簽名和加密服務,而數字證書以及證書機構(CA – Certificate Authority)是PKI中的重要概念。

看看這篇文章

雙向認證原理圖:


httpsyuanlitu.png

需要準備的自簽名證書

1.服務器私鑰 2.由CA簽發的含有服務器公鑰的數字證書 3.CA的數字證書。在雙向認證的實踐中,通常服務器可以自己作為證書機構,并且由服務器CA簽發服務器證書和客戶端證書。

1.客戶端私鑰 2. 由CA簽發的含有客戶端公鑰的數字證書。為了避免中間人攻擊,客戶端還需要內置服務器證書,用來驗證所連接的服務器是否是指定的服務器。

  • 服務端 .cer
  • 客戶端 .p12

使用AFNetworking 3.0

    NSString *certFilePath = [[NSBundle mainBundle] pathForResource:@"server" ofType:@"der"];
    NSData *certData = [NSData dataWithContentsOfFile:certFilePath];
    NSSet *certSet = [NSSet setWithObject:certData];
    AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:certSet];
    policy.allowInvalidCertificates = YES;
    policy.validatesDomainName = NO;
     
    _manager = [AFHTTPSessionManager manager];
    _manager.securityPolicy = policy;
    _manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    _manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    _manager.responseSerializer.acceptableContentTypes =  [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/plain", nil];
    //關閉緩存避免干擾測試r
    _manager.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
    [_manager setSessionDidBecomeInvalidBlock:^(NSURLSession * _Nonnull session, NSError * _Nonnull error) {
        DLog(@"setSessionDidBecomeInvalidBlock");
    }];
//客服端請求驗證 重寫 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([weakSelf.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 {
        // client authentication
        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 ([[weakSelf class]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;
            }
        }
    }
    *_credential = credential;
    return disposition;
}];
+(BOOL)extractIdentity:(SecIdentityRef*)outIdentity andTrust:(SecTrustRef *)outTrust fromPKCS12Data:(NSData *)inPKCS12Data {
    OSStatus securityError = errSecSuccess;
    //client certificate password
    NSDictionary*optionsDictionary = [NSDictionary dictionaryWithObject:@"你的p12密碼"
                                                                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;
}

完畢

  • 使用MKNetworkKit 與 使用蘋果官方原生 代碼片段 詳見Demo

Demo

https://github.com/cuiwe000/HttpsDemo.git

參考文檔

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容