ios - 在 iOS 应用程序中嵌入 SSL 根证书,而不是为整个系统安装它

标签 ios swift ssl ssl-certificate

如何在连接到本地服务器的应用程序中嵌入自定义 CA SSL 证书?

此证书应该像系统中安装的任何 CA 证书一样工作,但嵌入此应用程序而不是要求用户在系统范围内安装它,因此它不会显示安全警告并且仅适用于我们的本地服务器应用

这样做的需要是为了遵守 ATS,而不需要用户进行任何进一步的配置,例如手动下载和安装 CA 证书

最佳答案

我假设您使用的是自签名证书,在这种情况下,您需要的是SSL 固定

根据您是否使用网络库,这可能会有所不同,但您想要做的是存储一个公共(public)证书,然后手动处理身份验证质询:

https://developer.apple.com/documentation/foundation/url_loading_system/handling_an_authentication_challenge

例如:

func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {  
    guard let trust = challenge.protectionSpace.serverTrust, SecTrustGetCertificateCount(trust) > 0 else {
        // This case will probably get handled by ATS, but still...
        completionHandler(.cancelAuthenticationChallenge, nil)
        return
    }

    // Or, compare the public keys
    if let serverCertificate = SecTrustGetCertificateAtIndex(trust, 0), let serverCertificateKey = publicKey(for: serverCertificate) {
        if pinnedKeys().contains(serverCertificateKey) {
            completionHandler(.useCredential, URLCredential(trust: trust))
            return
        }
    }

    completionHandler(.cancelAuthenticationChallenge, nil)
}


fileprivate func pinnedKeys() -> [SecKey] {
    var publicKeys: [SecKey] = []

    if let pinnedCertificateURL = Bundle.main.url(forResource: "infinumco", withExtension: "crt") {
        do {
            let pinnedCertificateData = try Data(contentsOf: pinnedCertificateURL) as CFData
            if let pinnedCertificate = SecCertificateCreateWithData(nil, pinnedCertificateData), let key = publicKey(for: pinnedCertificate) {
                publicKeys.append(key)
            }
        } catch (_) {
            // Handle error
        }
    }

    return publicKeys
}

我这里有几个其他示例如何处理这种情况:

https://github.com/Adis/swift-ssl-pin-examples

关于ios - 在 iOS 应用程序中嵌入 SSL 根证书,而不是为整个系统安装它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54975933/

相关文章:

ios - AudioKit:如何点击同一输入进行多次使用(AudioKitUI + 语音识别)

ios/xcode/objective-c : Any way to link to other view controller in core-data driven page?

ios - 如何在我的代码中实现反调试?

ios - 如何在编辑表格 View 单元格中的文本字段时重新加载所有表格 View 单元格 - iOS Swift

swift - 不使用预定义函数反转字符串

java - 如何为camel-https4配置trustStore

email - smtp.live.com 没有回复 AUTH LOGIN

ios - Asihttprequest localizedDescription 总是英文

php - cURL 出现 SSL 依赖错误 libssl.so Ubuntu 32 位中需要 libcrypto.so

ios - 如何将选定的图像从 UIImagePickerController 传递到第二个 View Controller ?