title: Pinning PublicKey with AlamoFire
body: <p>I've been trying to perform a <a href="https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#Public_Key" rel="nofollow noreferrer">public key pinning</a> for my application.</p>
  
  <p>And I did the following steps:</p>
  
  <p>1) First I used openssl to extract the server cert in der format</p>
  
  <p><code>openssl s_client -showcerts -connect my.server.com:443 &lt; /dev/null | openssl x509 -outform DER &gt; serverCert.der</code></p>
  
  <p>2) Loaded publicKey from cert:</p>
  
  <pre><code>    func getPubKey() -&gt; 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, &amp;trust)
  
          var key: SecKey?
          if status == errSecSuccess {
              key = SecTrustCopyPublicKey(trust!)!;
              print("NetworkImplementation :: getPubKey :: success")
          }
          return key
      }
  </code></pre>
  
  <p>3) added my serverTrustPolicy to Alamofire’s Manager:</p>
  
  <pre><code>    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")
  </code></pre>
  
  <p>4) When I want to perform a request I do this:</p>
  
  <pre><code>self.afManager
          .request(almethod, url, parameters: alparams, encoding: encoding, headers: alheaders)
           .validate()
          .response { //... }
  </code></pre>
  
  <p>Then I tried to check if it was not trusting a self signed certificate, to do that I used <a href="https://www.charlesproxy.com" rel="nofollow noreferrer">Charles</a> and the iOS Simulator.</p>
  
  <p>After installing Charles, added my server domain to the SSL Proxy configuration on port 443 and clicked <strong>Help -> SSL Proxying -> Install on simulators</strong>.</p>
  
  <p>I was able to see the request and response content of my application inside the Charles UI and the request connection status was not an error.</p>
  
  <p>What am I missing?</p>