使用AlamoFire固定PublicKey

时间:2016-11-08 22:24:28

标签: ios swift ssl alamofire pinning

我一直在尝试为我的应用程序执行public key pinning

我做了以下步骤:

1)首先,我使用openssl以格式提取服务器证书

openssl s_client -showcerts -connect my.server.com:443 < /dev/null | openssl x509 -outform DER > serverCert.der

2)从cert:

加载的publicKey
    func getPubKey() -> SecKey? {
        let certificateData = NSData(contentsOfURL:NSBundle.mainBundle().URLForResource("serverCert", withExtension: "der")!)

        let certificate = SecCertificateCreateWithData(nil, certificateData!)

        var trust: SecTrustRef?

        let policy = SecPolicyCreateBasicX509()
        let status = SecTrustCreateWithCertificates(certificate!, policy, &trust)

        var key: SecKey?
        if status == errSecSuccess {
            key = SecTrustCopyPublicKey(trust!)!;
            print("NetworkImplementation :: getPubKey :: success")
        }
        return key
    }

3)将我的serverTrustPolicy添加到Alamofire的经理:

    let key: SecKey? = self.getPubKey()

    self.serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(publicKeys: [key!],
                                                             validateCertificateChain: true,
                                                             validateHost: true)

    self.serverTrustPolicies = [
        "*.my.server.com": self.serverTrustPolicy!
    ]

    self.afManager = Manager(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
                             serverTrustPolicyManager: ServerTrustPolicyManager(policies: self.serverTrustPolicies))

    print("NetworkImplementation :: init :: success")

4)当我想要执行请求时,我这样做:

self.afManager
        .request(almethod, url, parameters: alparams, encoding: encoding, headers: alheaders)
         .validate()
        .response { //... }

然后我尝试检查它是否不信任自签名证书,为此我使用了Charles和iOS模拟器。

安装Charles后,将我的服务器域添加到端口443上的SSL代理配置中,然后单击帮助 - &gt; SSL代理 - &gt;在模拟器上安装

我能够在Charles UI中看到我的应用程序的请求和响应内容,并且请求连接状态不是错误。

我错过了什么?

0 个答案:

没有答案