Skip to content

Instantly share code, notes, and snippets.

@lifeisfoo
Created March 3, 2016 18:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lifeisfoo/63478c8520d9c0f74477 to your computer and use it in GitHub Desktop.
Save lifeisfoo/63478c8520d9c0f74477 to your computer and use it in GitHub Desktop.
Swift version of OWASP's didReceiveAuthenticationChallenge method (for ios SSL PINNING) (complete method http://stackoverflow.com/a/34223292/3340702)
import Foundation
import Security
class NSURLSessionPinningDelegate: NSObject, NSURLSessionDelegate {
func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> 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(kSecTrustResultInvalid)
let status = SecTrustEvaluate(serverTrust, &secresult)
if(errSecSuccess == status) {
if let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) {
if let serverCertificateData = SecCertificateCopyData(serverCertificate) as? CFDataRef {
let data = CFDataGetBytePtr(serverCertificateData);
let size = CFDataGetLength(serverCertificateData);
let cert1 = NSData(bytes: data, length: size)
let file_der = NSBundle.mainBundle().pathForResource("my-https-website", ofType: "der")
if let file = file_der {
if let cert2 = NSData(contentsOfFile: file) {
if cert1.isEqualToData(cert2) {
completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, NSURLCredential(forTrust:serverTrust))
return
}
}
}
}
}
}
}
}
// Pinning failed
completionHandler(NSURLSessionAuthChallengeDisposition.CancelAuthenticationChallenge, nil)
}
}
@SaurabhGohel
Copy link

Want to add multiple Certificates how can I do it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment