phantomon

Untitled

Oct 19th, 2017
275
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.34 KB | None | 0 0
  1. func URLSession(session: NSURLSession,  didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
  2.     let serverTrust = challenge.protectionSpace.serverTrust
  3.     let certificate = SecTrustGetCertificateAtIndex(serverTrust!, 0)
  4.  
  5.     // Set SSL policies for domain name check
  6.     let policies = NSMutableArray();
  7.     policies.addObject(SecPolicyCreateSSL(true, (challenge.protectionSpace.host)))
  8.     SecTrustSetPolicies(serverTrust!, policies);
  9.  
  10.     // Evaluate server certificate
  11.     var result: SecTrustResultType = 0
  12.     SecTrustEvaluate(serverTrust!, &result)
  13.     let isServerTrusted:Bool = (Int(result) == kSecTrustResultUnspecified || Int(result) == kSecTrustResultProceed)
  14.  
  15.     // Get local and remote cert data
  16.     let remoteCertificateData:NSData = SecCertificateCopyData(certificate!)
  17.     let pathToCert = NSBundle.mainBundle().pathForResource(githubCert, ofType: "cer")
  18.     let localCertificate:NSData = NSData(contentsOfFile: pathToCert!)!
  19.  
  20.     if (isServerTrusted && remoteCertificateData.isEqualToData(localCertificate)) {
  21.         let credential:NSURLCredential = NSURLCredential(forTrust: serverTrust!)
  22.         completionHandler(.UseCredential, credential)
  23.     } else {
  24.         completionHandler(.CancelAuthenticationChallenge, nil)
  25.     }
  26. }
Advertisement
Add Comment
Please, Sign In to add comment