我从服务器获取p12文件。我需要在设备配置文件中安装该p12文件,该文件位于设置应用程序中。 以下是我的代码
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)
我在线打印时出现“意外发现零值”(证书!),因为证书无法生成。
那么请你帮助我。
提前致谢。