证书固定在Alamofire中 [英] Certificate pinning in Alamofire

查看:126
本文介绍了证书固定在Alamofire中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个访问HTTPS Web服务的iPad应用。我想实现固定,但是遇到了问题。

I am creating an iPad app that accesses HTTPS web services. I want to implement pinning, but am having issues.

该类创建Alamofire管理器(大部分取自文档):

This class creates the Alamofire Manager (mostly taken from documentation):

class NetworkManager {

    var manager: Manager?

    init() {
        let serverTrustPolicies: [String: ServerTrustPolicy] = [
            "www.google.co.uk": .PinCertificates(
                certificates: ServerTrustPolicy.certificatesInBundle(),
                validateCertificateChain: true,
                validateHost: true
            ),
            "insecure.expired-apis.com": .DisableEvaluation
        ]

        manager = Alamofire.Manager(
            configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
            serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
        )
    }
}

此函数进行调用:

static let networkManager = NetworkManager()

public static func testPinning() {
    networkManager.manager!.request(.GET, "https://www.google.co.uk").response { response in
        if response.1 != nil {
            print("Success")
            print(response.1)
            print(response.1?.statusCode)
        } else {
            print("Error")
            print(response.3)
        }
    }
}

证书已保存在项目中,并显示在目标>构建阶段>复制捆绑资源下。

The certificate is saved in the project and shows under 'Targets > Build Phases > Copy Bundle Resources'.

我每次发出请求时都收到以下错误(来自 testPinning()中的else块) >):

I am currently receiving the following error every time I make the request (from the else block in testPinning()):

Optional(Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo={NSErrorFailingURLKey=https://www.google.co.uk/, NSLocalizedDescription=cancelled, NSErrorFailingURLStringKey=https://www.google.co.uk/})


推荐答案

因此,问题在于证书以错误的格式保存。

So, the issue was that the certificate was saved in the wrong format.

ServerTrustPolicy.certificatesIn Bundle()根据扩展列表查找捆绑中的所有证书,然后尝试使用 SecCertificateCreateWithData 加载它们。根据其文档,此函数:

ServerTrustPolicy.certificatesInBundle() finds all certificates in the bundle based on a list of extensions, then tries to load them using SecCertificateCreateWithData. Per its documentation, this function:


如果在data参数中传递的数据不是有效的
DER编码,则返回NULL X.509证书

Returns NULL if the data passed in the data parameter is not a valid DER-encoded X.509 certificate

在Firefox中导出证书时,文件底部会弹出格式浏览器。选择 X.509证书(DER),您将为此获得正确格式的证书。

When you export a certificate in Firefox, you have a "format" pop-up at the bottom of the file browser. Select "X.509 Certificate (DER)", and you should get a certificate in the right format for this purpose.

这篇关于证书固定在Alamofire中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆