国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Swift - 使用Alamofire通過HTTPS進行網絡請求,及證書的使用

2019-11-09 15:14:34
字體:
來源:轉載
供稿:網友
(本文代碼已升級至Swift3) 我原來寫過一篇文章介紹如何使用證書通過SSL/TLS方式進行網絡請求(Swift - 使用URLsession通過HTTPS進行網絡請求,及證書的使用),當時用的是URLSession。本文介紹如何使用 Alamofire 來實現HTTPS網絡請求,由于Alamofire就是對URLSession的封裝,所以實現起來區別不大。(如果Alamofire的配置使用不了解的,可以先去看看我原來寫的文章:Swift - HTTP網絡操作庫Alamofire使用詳解)一,證書的生成,以及服務器配置參考我前面寫的這篇文章:Tomcat服務器配置https雙向認證(使用keytool生成證書)文章詳細介紹了HTTPS,SSL/TLS。還有使用key tool生成自簽名證書,Tomcat下https服務的配置。二,Alamofire使用HTTPS進行網絡請求1,證書導入前面文章介紹了通過客戶端瀏覽器訪問HTTPS服務需,需要安裝“mykey.p12”,“tomcat.cer”這兩個證書。同樣,我們開發的應用中也需要把這兩個證書添加進來。原文:Swift - 使用Alamofire通過HTTPS進行網絡請求,及證書的使用記的同時在 “工程” -> “Build Phases” -> “Copy Bundle Resources” 中添加這兩個證書文件。原文:Swift - 使用Alamofire通過HTTPS進行網絡請求,及證書的使用2,配置Info.plist由于我們使用的是自簽名的證書,而蘋果ATS(App Transport Security)只信任知名CA頒發的證書,所以在iOS9下即使是HTTPS請求還是會被ATS攔截。所以在Info.plist下添加如下配置(iOS8不需要):
12345<key>NSAPPTransportSecurity</key><dict>    <key>NSAllowsArbitraryLoads</key>    <true/></dict>
3,使用兩個證書進行雙向驗證,以及網絡請求
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111import UIKitimport Alamofire class ViewController: UIViewController{         overridefunc viewDidLoad() {        super.viewDidLoad()                 //認證相關設置        letmanager = SessionManager.default        manager.delegate.sessionDidReceiveChallenge = { session, challengein            //認證服務器證書            ifchallenge.PRotectionSpace.authenticationMethod                ==NSURLAuthenticationMethodServerTrust {                print("服務端證書認證!")                letserverTrust:SecTrust= challenge.protectionSpace.serverTrust!                letcertificate = SecTrustGetCertificateAtIndex(serverTrust, 0)!                letremoteCertificateData                    =CFBridgingRetain(SecCertificateCopyData(certificate))!                letcerPath = Bundle.main.path(forResource:"tomcat", ofType:"cer")!                letcerUrl = URL(fileURLWithPath:cerPath)                letlocalCertificateData = try! Data(contentsOf: cerUrl)                                 if(remoteCertificateData.isEqual(localCertificateData) ==true) {                                         letcredential = URLCredential(trust: serverTrust)                    challenge.sender?.use(credential,for: challenge)                    return(URLSession.AuthChallengeDisposition.useCredential,                            URLCredential(trust: challenge.protectionSpace.serverTrust!))                                     }else {                    return(.cancelAuthenticationChallenge, nil)                }            }            //認證客戶端證書            elseif challenge.protectionSpace.authenticationMethod                ==NSURLAuthenticationMethodClientCertificate{                print("客戶端證書認證!")                //獲取客戶端證書相關信息                letidentityAndTrust:IdentityAndTrust= self.extractIdentity();                                 leturlCredential:URLCredential= URLCredential(                    identity: identityAndTrust.identityRef,                    certificates: identityAndTrust.certArrayas? [AnyObject],                    persistence:URLCredential.Persistence.forSession);                                 return(.useCredential, urlCredential);            }            // 其它情況(不接受認證)            else{                print("其它情況(不接受認證)")                return(.cancelAuthenticationChallenge, nil)            }        }                 //數據請求        Alamofire.request("https://192.168.1.112:8443")            .responseString { responsein                print(response)        }    }         //獲取客戶端證書相關信息    funcextractIdentity() -> IdentityAndTrust{        varidentityAndTrust:IdentityAndTrust!        varsecurityError:OSStatus= errSecSuccess                 letpath: String = Bundle.main.path(forResource:"mykey", ofType:"p12")!        letPKCS12Data = NSData(contentsOfFile:path)!        letkey : NSString= kSecImportExportPassphrase asNSString        letoptions : NSDictionary= [key : "123456"]//客戶端證書密碼        //create variable for holding security information        //var privateKeyRef: SecKeyRef? = nil                 varitems : CFArray?                 securityError =SecPKCS12Import(PKCS12Data, options, &items)                 ifsecurityError == errSecSuccess {            letcertItems:CFArray= items as CFArray!;            letcertItemsArray:Array= certItems asArray            letdict:AnyObject? = certItemsArray.first;            iflet certEntry:Dictionary= dict as?Dictionary<String,AnyObject> {                // grab the identity                letidentityPointer:AnyObject? = certEntry["identity"];                letsecIdentityRef:SecIdentity= identityPointer as!SecIdentity!                print("/(identityPointer)  :::: /(secIdentityRef)")                // grab the trust                lettrustPointer:AnyObject? = certEntry["trust"]                lettrustRef:SecTrust= trustPointer as!SecTrust                print("/(trustPointer)  :::: /(trustRef)")                // grab the cert                letchainPointer:AnyObject? = certEntry["chain"]                identityAndTrust =IdentityAndTrust(identityRef: secIdentityRef,                                        trust: trustRef, certArray:  chainPointer!)            }        }        returnidentityAndTrust;    }         overridefunc didReceiveMemoryWarning() {        super.didReceiveMemoryWarning()    }} //定義一個結構體,存儲認證相關信息structIdentityAndTrust {    varidentityRef:SecIdentity    vartrust:SecTrust    varcertArray:AnyObject}
控制臺打印輸出如下:原文:Swift - 使用Alamofire通過HTTPS進行網絡請求,及證書的使用4,只使用一個客戶端證書由于我們使用的是自簽名的證書,那么對服務器的認證全由客戶端這邊判斷。也就是說其實使用一個客戶端證書“mykey.p12”也是可以的(項目中也只需導入一個證書)。當對服務器進行驗證的時候,判斷服務主機地址是否正確,是的話信任即可(代碼高亮部分)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899import UIKitimport Alamofire class ViewController: UIViewController{         //自簽名網站地址    letselfSignedHosts = ["192.168.1.112","www.hangge.com"]         overridefunc viewDidLoad() {        super.viewDidLoad()                 //認證相關設置        letmanager = SessionManager.default        manager.delegate.sessionDidReceiveChallenge = { session, challengein            //認證服務器(這里不使用服務器證書認證,只需地址是我們定義的幾個地址即可信任)            ifchallenge.protectionSpace.authenticationMethod                ==NSURLAuthenticationMethodServerTrust                &&self.selfSignedHosts.contains(challenge.protectionSpace.host) {                print("服務器認證!")                letcredential = URLCredential(trust: challenge.protectionSpace.serverTrust!)                return(.useCredential, credential)            }            //認證客戶端證書            elseif challenge.protectionSpace.authenticationMethod                ==NSURLAuthenticationMethodClientCertificate{                print("客戶端證書認證!")                //獲取客戶端證書相關信息                letidentityAndTrust:IdentityAndTrust= self.extractIdentity();                                 leturlCredential:URLCredential= URLCredential(                    identity: identityAndTrust.identityRef,                    certificates: identityAndTrust.certArrayas? [AnyObject],                    persistence:URLCredential.Persistence.forSession);                                 return(.useCredential, urlCredential);            }            // 其它情況(不接受認證)            else{                print("其它情況(不接受認證)")                return(.cancelAuthenticationChallenge, nil)            }        }                 //數據請求        Alamofire.request("https://192.168.1.112:8443")            .responseString { responsein                print(response)        }    }         //獲取客戶端證書相關信息    funcextractIdentity() -> IdentityAndTrust{        varidentityAndTrust:IdentityAndTrust!        varsecurityError:OSStatus= errSecSuccess                 letpath: String = Bundle.main.path(forResource:"mykey", ofType:"p12")!        letPKCS12Data = NSData(contentsOfFile:path)!        letkey : NSString= kSecImportExportPassphrase asNSString        letoptions : NSDictionary= [key : "123456"]//客戶端證書密碼        //create variable for holding security information        //var privateKeyRef: SecKeyRef? = nil                 varitems : CFArray?                 securityError =SecPKCS12Import(PKCS12Data, options, &items)                 ifsecurityError == errSecSuccess {            letcertItems:CFArray= items as CFArray!;            letcertItemsArray:Array= certItems asArray            letdict:AnyObject? = certItemsArray.first;            iflet certEntry:Dictionary= dict as?Dictionary<String,AnyObject> {                // grab the identity                letidentityPointer:AnyObject? = certEntry["identity"];                letsecIdentityRef:SecIdentity= identityPointer as!SecIdentity!                print("/(identityPointer)  :::: /(secIdentityRef)")                // grab the trust                lettrustPointer:AnyObject? = certEntry["trust"]                lettrustRef:SecTrust= trustPointer as!SecTrust                print("/(trustPointer)  :::: /(trustRef)")                // grab the cert                letchainPointer:AnyObject? = certEntry["chain"]                identityAndTrust =IdentityAndTrust(identityRef: secIdentityRef,                                        trust: trustRef, certArray:  chainPointer!)            }        }        returnidentityAndTrust;    }         overridefunc didReceiveMemoryWarning() {        super.didReceiveMemoryWarning()    }} //定義一個結構體,存儲認證相關信息structIdentityAndTrust {    varidentityRef:SecIdentity    vartrust:SecTrust    varcertArray:AnyObject}

原文出自:www.hangge.com  轉載請保留原文鏈接:http://www.hangge.com/blog/cache/detail_1052.html
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 丹巴县| 江口县| 二连浩特市| 孝昌县| 新野县| 沙坪坝区| 游戏| 开远市| 武强县| 莱阳市| 汉川市| 林西县| 遂昌县| 中山市| 长岭县| 蓬莱市| 大连市| 乃东县| 广昌县| 西城区| 达孜县| 通城县| 宁阳县| 清水县| 和硕县| 仁寿县| 西城区| 克山县| 隆回县| 山丹县| 宣汉县| 长乐市| 西峡县| 剑川县| 延长县| 夏津县| 彰化县| 汤原县| 兴文县| 通城县| 中山市|