[英]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.