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

使用Swift和NSURLSession固定的​​iOS证书,第1张

概述如何在Swift中将证书固定添加到NSURLSession? OWASP website仅包含Objective-C和NSURLConnection的示例. Swift 3更新: 只需为NSURLSessionDelegate定义一个委托类并实现didReceiveChallenge函数(此代码改编自objective-c OWASP示例): class NSURLSessionPinningDe 如何在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")}
总结

以上是内存溢出为你收集整理的使用Swift和NSURLSession固定的​​iOS证书全部内容,希望文章能够帮你解决使用Swift和NSURLSession固定的​​iOS证书所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1049883.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存