0

我使用NEVPNManagerIKEV2 证书作为连接 VPN 的身份验证方法。我能够连接到 VPN。下面提到的是我的示例代码块。

 guard let path = Bundle.main.path(forResource: VPNConstants.certificateName, ofType: ".p12")  else {
        fatalError("Unable to find Certificate")
    }
    do {
        let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
        ikev2.identityData = data
    }
    catch {
        fatalError("Unable to find Certificate")
    }
    ikev2.identityDataPassword = VPNConstants.password 

我尝试使用安全框架的 SecCertificateCreateWithData 和 SecItemAdd 方法安装根证书,安装证书时没有收到任何错误,但它没有出现在我的 iOS 配置文件和设备管理以及 TrustStore 中。下面是我使用的代码块。

fileprivate func installCertificate() {
        guard let path = Bundle.main.path(forResource: "rootcertificate", ofType: "der") else {
            return
        }
    
        do {
            let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
            var status: OSStatus = noErr
            guard let rootCert = SecCertificateCreateWithData(nil, data as CFData) else {
                return
            }
            
            let addquery: [String: Any] = [kSecClass as String: kSecClassCertificate,
                                           kSecValueRef as String: rootCert,
                                           kSecAttrLabel as String: "My Certificate"]
            status = SecItemAdd(addquery as CFDictionary, nil)
            if status == noErr {
                print("Install root certificate success")
            }
            else if  status == errSecDuplicateItem {
                print("duplicate root certificate entry")
            }
            else {
                print("install root certificate failure")
            }
    
            let policy = SecPolicyCreateBasicX509()
            var optionalTrust: SecTrust?
            let certArray = [rootCert]
            status = SecTrustCreateWithCertificates(certArray as AnyObject,
                                                    policy,
                                                    &optionalTrust)
            guard status == errSecSuccess else {
                return
            }
            let trust = optionalTrust!
            var trustResult = SecTrustResultType.invalid
            status = SecTrustEvaluate(trust, &trustResult)
            print(trust)
            if status == noErr {
                print("Trust root certificate success")
            }
            else if  status == errSecDuplicateItem {
                print("Trust Fail")
            }
            else {
                print("Trust Fail")
            }
        }
    
        catch {
            print("Trust root certificate failure")
        }
    
    }

目前,我正在通过 Safari 或 Mail 安装根证书。另外,我的根证书是自签名的。我知道只有由受信任的 CA 签名才能启用证书信任,但我如何至少将其添加到 iOS 配置文件和设备管理中。

任何帮助表示赞赏,在此先感谢!!!

4

1 回答 1

0

经过大量研究和浏览后,我得出结论,Apple 不允许您以编程方式安装根证书。对于 iOS,使用 Personal VPN (NEVPNManager),我们应该使用已经包含在设备信任库中的根证书。

于 2020-07-15T04:41:34.840 回答