How do I install a root certificate authority on a device?
The certificate is only needed for my app, and can be installed in its sandbox if possible.
It works when I drag the certificate onto the simulator and install it, but not using the following code:
let rootCertPath = NSBundle.mainBundle().pathForResource("server", ofType: "der")!
let rootCertData = NSData(contentsOfFile: rootCertPath)!
let rootCert = SecCertificateCreateWithData(kCFAllocatorDefault, rootCertData).takeRetainedValue()
let error = SecItemAdd(
[
NSString(format: kSecClass): NSString(format: kSecClassCertificate),
NSString(format: kSecValueRef): rootCert
], nil)
SecItemAdd
returns with no errors, and seems to be installed on the device correctly, but it still fails to connect to the server with with the error:
NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)
Code for connecting to server:
let request = NSURLRequest(URL: NSURL(string: "https://" + server + ":" + port)!)
let session = NSURLSession(configuration: .defaultSessionConfiguration())
session.dataTaskWithRequest(request, completionHandler:
{(data, response, error) in
println(error)
}).resume()
error
prints the following:
Error Domain=NSURLErrorDomain Code=-1202 "The certificate for this server is invalid.
But again, if I manually install the same certificate in the simulator's profiles, it connects just fine.