Created
February 11, 2023 18:41
-
-
Save rodnt/80045ddf8970643a6db1d3b30a11ec9d to your computer and use it in GitHub Desktop.
Custom SSLPinning iOS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { | |
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: "name-of-cert-file", ofType: "cer") | |
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) | |
} | |
/*Izi way using Alamofire*/ | |
let pathToCert = Bundle.main.path(forResource: “name-of-cert-file”, ofType: “cer”) | |
let localCertificate : NSData = NSData(contentsOfFile: pathToCert! )! | |
let serverTrustPolicy = ServerTrustPolicy.pinCertificates( | |
certificates : [SecCertificateCreateWithData(nil, localCertificate) !], | |
validateCertificateChain : true, | |
validateHost : true | |
) | |
let serverTrustPolicies = [ | |
“my-server.com” : serverTrustPolicy | |
] | |
let sessionManager = SessionManager ( | |
serverTrustPolicyManager : ServerTrustPolicyManager(policies : serverTrustPolicies) | |
) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment