[英]Why is Alamofire public key pinning not working?
我正在嘗試使用 Alamofire 和 Moya 執行公鑰固定。
我正在構建自己的自定義 Alamofire 會話並將其傳遞給我的 Moya 提供者。 我已經閱讀了 Alamofire 關於如何執行公鑰固定的文檔,這些文檔總結了這幾行代碼:
let configuration = URLSessionConfiguration.default
let trustManager = ServerTrustManager(evaluators: ["domain.example.com": PublicKeysTrustEvaluator()])
return MySession(configuration: configuration, serverTrustManager: trustManager)
我的理解是 PublicKeysTrustEvaluator() 將過濾在 Bundle.main 中找到的所有證書並提取公鑰並對主機執行公鑰固定。 如果至少有一個成功,則服務器信任被認為是有效的。
以下是 Alamofire 項目的一些代碼:
extension AlamofireExtension where ExtendedType: Bundle {
/// Returns all valid `cer`, `crt`, and `der` certificates in the bundle.
public var certificates: [SecCertificate] {
paths(forResourcesOfTypes: [".cer", ".CER", ".crt", ".CRT", ".der", ".DER"]).compactMap { path in
guard
let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData,
let certificate = SecCertificateCreateWithData(nil, certificateData) else { return nil }
return certificate
}
}
/// Returns all public keys for the valid certificates in the bundle.
public var publicKeys: [SecKey] {
certificates.af.publicKeys
}
如果函數SecCertificateCreateWithData
只需要 DER 格式,為什么 Alamofire 允許使用 .cer/.crt 文件?
函數路徑正在返回我的 .cer 文件,但 Bundle.main.af.publicKeys 為空,因為此調用SecCertificateCreateWithData
總是失敗。
我應該將我的證書轉換為 DER 格式嗎?
如果是這樣,我該怎么做?
上面提到的函數paths(forResourcesOfTypes
)找不到此調用的輸出。
openssl x509 -outform der -in certificatename.pem -out certificatename.der
更新
我發現我的證書不正確。 我用另一種 .cer 格式替換了它,這一次,我沒有出錯。 然而,我所有的 API 調用都會導致 405 錯誤,即使這段代碼來自 Alamofire 代碼:
if !pinnedKeysInServerKeys {
throw AFError.serverTrustEvaluationFailed(reason: .publicKeyPinningFailed(host: host, trust: trust, pinnedKeys: keys, serverKeys: trust.af.publicKeys))
}
返回一個假。 那么,這是否意味着服務器信任評估沒有失敗?
您只需在應用程序包中添加您的信任認證即可使其工作。 只需確保添加正確的服務器證書即可。 就這樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.