Sai Reddy 的解决方案允许您接受具有完整链的自签名证书,但它也接受其他证书。
Marcus Leon 的解决方案是完全覆盖——基本上忽略所有证书。
我更喜欢这个。
Swift 4.1、iOS 11.4.1
首先,在您的 Info.plist 中:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
其次,无论您在何处使用 NSURLSession,而不是使用 URLSession.shared 进行设置,请使用以下内容:
session = URLSession(configuration: .default, delegate: APIURLSessionTaskDelegate(isSSLPinningEnabled: isSSLPinningEnabled), delegateQueue: nil)
然后添加这个类来处理固定:
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
print("*** received SESSION challenge...\(challenge)")
let trust = challenge.protectionSpace.serverTrust!
let credential = URLCredential(trust: trust)
guard isSSLPinningEnabled else {
print("*** SSL Pinning Disabled -- Using default handling.")
completionHandler(.useCredential, credential)
return
}
let myCertName = "my_certificate_to_pin"
var remoteCertMatchesPinnedCert = false
if let myCertPath = Bundle.main.path(forResource: myCertName, ofType: "der") {
if let pinnedCertData = NSData(contentsOfFile: myCertPath) {
// Compare certificate data
let remoteCertData: NSData = SecCertificateCopyData(SecTrustGetCertificateAtIndex(trust, 0)!)
if remoteCertData.isEqual(to: pinnedCertData as Data) {
print("*** CERTIFICATE DATA MATCHES")
remoteCertMatchesPinnedCert = true
}
else {
print("*** MISMATCH IN CERT DATA.... :(")
}
} else {
print("*** Couldn't read pinning certificate data")
}
} else {
print("*** Couldn't load pinning certificate!")
}
if remoteCertMatchesPinnedCert {
print("*** TRUSTING CERTIFICATE")
completionHandler(.useCredential, credential)
} else {
print("NOT TRUSTING CERTIFICATE")
completionHandler(.rejectProtectionSpace, nil)
}
}
}
此类检查您是否启用了证书固定。如果你这样做了,它会完全忽略正常的证书验证,并与我们在应用程序中包含的证书进行精确比较。这样,它只接受您的自签名证书,而不接受其他任何东西。
此解决方案要求您将“my_certificate_to_pin.der”文件放入项目的 Resources 文件夹中。如果您还没有 Resources 文件夹,只需添加一个即可。
该证书应为 DER 格式。
要为您的服务器创建自签名证书,您通常会执行以下操作:
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout mycert.key -out mycert.cer
这会生成两个文件——一个mycert.key私钥文件和一个mycert.cer——证书本身。这些都是 X509 格式。对于 iOS,您将需要 DER 格式的证书,请执行以下操作:
openssl x509 -outform der -in mycert.cer -out my_certificate_to_pin.der
这会生成您在 iOS 上需要的文件。