Alamofire SSL Pining

Alamofire是一个Swift http network library。用Alamofire做SSL Pining非常方便。CA证书的提取请参考上一篇文章。(需要注意的是iOS中需要提取DER格式的CA证书,而不是PEM。在保存证书时可以选择格式)

 

1
2
3
4
5
6
7
8
9
10
11
12
    let pathToCert = NSBundle.mainBundle().pathForResource("certificate", ofType: "cer")
    let localCertificate: NSData = NSData(contentsOfFile: pathToCert!)!
 
    let serverTrustPolicy = ServerTrustPolicy.PinCertificates(certificates: [SecCertificateCreateWithData(nil, localCertificate)!], validateCertificateChain: true, validateHost: true)
 
    let policies: [String: ServerTrustPolicy] = [
        "google.com": serverTrustPolicy
    ]
 
    let manager = Alamofire.Manager(serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies))
    // make your request here
    // manager.request(...)

Leave a Reply