1

I'm developing an iOS app that needs to do a HTTPS POST on a remote server. Here's what I want to do:

        // How to initialize 'credential' with a certificate.der (or .pem)
        var credential: URLCredential? 
        let pms: [String: Any] = ["func": "os.getpid"]
        Alamofire.request("https://mytestdomain.mycom/exec", method: .post, 
          parameters: pms, encoding: JSONEncoding.default, headers: nil)
          .authenticate(usingCredential: credential!)
          .responseJSON { response in
          if response.result.isSuccess {
              print("Success")
          }
          else {
              print("Error")
          }

But I haven't found a way to initialize the credential with a certificate. Is it possible?

Nishant S
  • 111
  • 3

1 Answers1

0

I don't know about DER or PEM.. but for p12, you can do:

private func loadCertificate(name: String, password: String?) throws -> (identity: SecIdentity, certificate: SecCertificate) {
    let path = Bundle.main.path(forResource: name, ofType: "p12")!
    let data = NSData(contentsOfFile: path)!
    let certificate = SecCertificateCreateWithData(nil, data)!

    let options = [String(kSecImportExportPassphrase):password ?? ""]
    var items: CFArray? = nil
    let result = SecPKCS12Import(data, options as CFDictionary, &items)

    if (result != errSecSuccess) {
        throw RuntimeError("Cannot Import Certificte")
    }

    let info = (items! as NSArray).firstObject! as! NSDictionary
    let identity = info[String(kSecImportItemIdentity)] as! SecIdentity
    return (identity, certificate)
}

Then:

let info = try loadCertificate(name: "MyCertificate", password: "Password..")
let credentials = URLCredential(identity: info.identity, certificates: [info.certificate], persistence: .forSession)
Brandon
  • 22,723
  • 11
  • 93
  • 186
  • Tried with p12, and got this: `Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value` Offending line of code: let certificate = SecCertificateCreateWithData(nil, data)! – Nishant S Sep 28 '18 at 02:17
  • @phoebus Nope, I decided to just move on to React-Native instead. – Nishant S Feb 18 '19 at 00:36
  • For people having the same question, this eventually helped me: https://stackoverflow.com/questions/39985856/getting-client-certificate-to-work-for-mutual-authentication-using-swift-3-and-a – phoebus Feb 19 '19 at 19:29