栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用Swift和NSURLSession固定iOS证书

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Swift和NSURLSession固定iOS证书

Swift 3+ 更新:

只需定义一个委托类

NSURLSessionDelegate
并实现didReceiveChallenge函数( 此代码改编自Objective-c
OWASP示例
):

class NSURLSessionPinningDelegate: NSObject, URLSessionDelegate {    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void) {        // Adapted from OWASP https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#iOS        if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) { if let serverTrust = challenge.protectionSpace.serverTrust {     let isServerTrusted = SecTrustevaluateWithError(serverTrust, nil)     if(isServerTrusted) {         if let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) {  let serverCertificateData = SecCertificateCopyData(serverCertificate)  let data = CFDataGetBytePtr(serverCertificateData);  let size = CFDataGetLength(serverCertificateData);  let cert1 = NSData(bytes: data, length: size)  let file_der = Bundle.main.path(forResource: "certificateFile", ofType: "der")  if let file = file_der {      if let cert2 = NSData(contentsOfFile: file) {          if cert1.isEqual(to: cert2 as Data) {   completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust:serverTrust))   return          }      }  }         }     } }        }        // Pinning failed        completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)    }}

(您可以在此处找到Swift
2
的Gist-
从初始答案开始)

然后使用创建

.der
网站的文件
openssl

openssl s_client -connect my-https-website.com:443 -showcerts < /dev/null | openssl x509 -outform DER > my-https-website.der

并将其添加到xpre项目。仔细检查列表中的

Build phases
标签中是否存在该标签
Copy BundleResources
。否则,将其拖放到此列表中。

最后在代码中使用它来发出URL请求:

if let url = NSURL(string: "https://my-https-website.com") {    let session = URLSession( configuration: URLSessionConfiguration.ephemeral, delegate: NSURLSessionPinningDelegate(), delegateQueue: nil)    let task = session.dataTask(with: url as URL, completionHandler: { (data, response, error) -> Void in        if error != nil { print("error: (error!.localizedDescription): (error!)")        } else if data != nil { if let str = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) {     print("Received data:n(str)") } else {     print("Unable to convert data to text") }        }    })    task.resume()} else {    print("Unable to create NSURL")}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/426976.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号