Can't able to install p12 file on iPhone

241 views Asked by At

I'm getting a p12 file from server. I need to install that p12 file in device profiles, which is in settings app. Below is my code

var documentsDirectory: NSURL?
var fileURL: NSURL?

documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last! as NSURL
fileURL = documentsDirectory!.appendingPathComponent("AuthRsa.p12")! as NSURL

if (fileURL!.checkResourceIsReachableAndReturnError(nil)) {
     print("file exist")
}else{
     print("file doesn't exist")
     do {
             try p12FileData.write(to: fileURL! as URL)
        } catch {
             print(error)
        }
}
print(fileURL!)
let p12Data: NSData = NSData(contentsOfFile: fileURL!.path!)!
let key : NSString = kSecImportExportPassphrase as NSString
let options : NSDictionary = [key : "test"]

var rawItems : CFArray?

let securityError: OSStatus = SecPKCS12Import(p12Data, options, &rawItems)
print(securityError)

let items = rawItems! as! Array<Dictionary<String, Any>>
let firstItem = items[0]
let identity = firstItem[kSecImportItemIdentity as String] as! SecIdentity?
let trust = firstItem[kSecImportItemTrust as String] as! SecTrust?

let ptr = p12Data.bytes.assumingMemoryBound(to: UInt8.self)

let cfData = CFDataCreate(kCFAllocatorDefault, ptr, p12Data.length)
let cert:SecCertificate? = SecCertificateCreateWithData(kCFAllocatorDefault, cfData!)
print(cert!)
let addquery: [String: Any] = [kSecClass as String: kSecClassCertificate, kSecValueRef as String: certificate!, kSecAttrLabel as String: "My Certificate"]         
let status = SecItemAdd(addquery as CFDictionary, nil)
print(status)

I'm getting crash "Unexpectedly found nil value" at the line print(cert!), because certificate is not able to generating.

So can you please help me.

Thanks in advance.

0

There are 0 answers