加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用Swift和NSURLSession固定的??iOS证书

发布时间:2020-12-14 05:46:27 所属栏目:百科 来源:网络整理
导读:如何在Swift中将证书固定添加到NSURLSession? OWASP website仅包含Objective-C和NSURLConnection的示例. Swift 3更新: 只需为NSURLSessionDelegate定义一个委托类并实现didReceiveChallenge函数(此代码改编自objective-c OWASP示例): class NSURLSessionP
如何在Swift中将证书固定添加到NSURLSession?

OWASP website仅包含Objective-C和NSURLConnection的示例.

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 {
                var secresult = SecTrustResultType.invalid
                let status = SecTrustEvaluate(serverTrust,&secresult)

                if(errSecSuccess == status) {
                    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)
    }

}

(你可以找到一个Gist for Swift 2 here – from the initial answer)

然后使用openssl为您的网站创建.der文件

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

并将其添加到xcode项目中.仔细检查它是否存在于“复制包资源”列表中的“构建阶段”选项卡中.否则将其拖放到此列表中.

最后在您的代码中使用它来发出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")
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读